我正在尝试将zip函数实现为Array的扩展,我打算像这样使用它:
let myKeys = ["a","b","c"]
let myVars = [1,2,3]
myKeys.zip(myVars) // ["a":1,"b":2,"c":3]
这是我的尝试:
extension Array {
public func zip<T,U>(vals: [U]) -> [T:U] {
var dict: [T:U] = Dictionary()
for (i,key) in self.enumerate() {
if let k = key as? T {
dict[k] = vals[i]
}
}
return dict
}
}
let myKeys = ["a","b","c"]
let myVars = [1,2,3]
myKeys.zip(myVars) // ERROR: Cannot convert value of type '[Int]' to expected argument type '[_]'
在最后一行,我收到一个我不完全理解的错误。我理解这意味着我正在传递一个[Int]而且它期待一个[_]。但这不是_只是一个通用的占位符吗?为什么会抱怨收到[Int]?
另外,如果我将zip作为类函数实现它没有问题:
class func zip<T,U>(keys keys: [T], vals: [U]) -> [T:U] {
var dict: [T:U] = Dictionary()
for (i,key) in keys.enumerate() {
dict[key] = vals[i]
}
return dict
}
zip(keys: myKeys,vals: myVals) // ["a":1,"b":2,"c":3]
对此的任何想法都将非常感激!
答案 0 :(得分:2)
请注意Array
已经有关联的类型,它被称为Element
,因此无需声明T
。您的代码的问题在于您无法将Element
转换为未定义的类型T
(T
与数组元素类型之间没有连接。)
extension Array where Element: Hashable {
public func zip<U>(vals: [U]) -> [Element: U] {
var dict: [Element: U] = Dictionary()
for (i, key) in self.enumerate() {
dict[key] = vals[i]
}
return dict
}
}
let myKeys = ["a","b","c"]
let myVars = [1,2,3]
let map = myKeys.zip(myVars)
print(map)
另请注意,我已为密钥添加了Hashable
要求。