Swift通用约束中的元组类型

Dun*_*can 2 generics tuples swift

我试图在Swift中编写一个泛型函数,其约束条件是参数必须是一对数组(我将把它变成一个字典).这可能吗?我已经尝试了以下几种变体,但编译器不喜欢它们中的任何一种.

func foo<K, V, S: SequenceType where S.Generator.Element == (K,V)>(xs: S) { //...}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 6

不是你的问题的直接答案,但如果你想创建一个字典,那么你可以将你的函数定义为扩展方法Dictionary并使用Dictionary定义的事实

typealias Element = (Key, Value)
Run Code Online (Sandbox Code Playgroud)

然后你的方法声明可以

extension Dictionary {
    func foo<S : SequenceType where S.Generator.Element == Element>(xs : S) {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

例如,要从元组创建字典,init方法可能更合适

extension Dictionary {

    init<S : SequenceType where S.Generator.Element == Element>(xs : S) {

        self.init()
        var gen = xs.generate()
        while let (key, value) : Element = gen.next() {
            self[key] = value
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

let d = Dictionary(xs: [("a", 1), ("b", 2)])
println(d) // [b: 2, a: 1]
Run Code Online (Sandbox Code Playgroud)

注:通过enumation generate()next()在上面的代码是针对该问题的解决方法是,由于某种原因

for (key, value) in xs { }
Run Code Online (Sandbox Code Playgroud)

不编译.比较在Swift中实现Set.addSequence.


更新:Swift 2/Xcode 7开始,上述方法可以简化为

extension Dictionary {

    init<S : SequenceType where S.Generator.Element == Element>(xs : S) {
        self.init()
        xs.forEach { (key, value) in
            self[key] = value
        }
    }
}
Run Code Online (Sandbox Code Playgroud)