swift-无法将类型"[Int]"的值转换为预期的参数类型"[_]"

swift-无法将类型

问题描述:

我正在尝试将zip函数实现为Array的扩展,并且打算将其像这样使用:

I'm trying to implement a zip function as an extension to Array, and I'm intending for it to be used like this:

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]?

On the last line I am getting an error that I do not completely understand. I understand it to mean that I'm passing an [Int] and it's expecting an [_]. But isn't _ just a generic placeholder here? Why would it complain about receiving an [Int]?

此外,如果我将zip实现为类函数,则没有问题:

Also, if I implement zip as a class function it has no issues:

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]

任何对此的想法将不胜感激!

Any thoughts on this would be much appreciated!

请注意,Array已经具有关联的类型,称为Element,因此无需声明T.代码的问题在于,您无法真正将Element转换为未定义的类型T(T与数组元素类型之间没有连接).

Note that Array already has an associated type, it's called Element, so no need to declare T. The problem with your code is that you cannot really convert an Element to undefined type T (there is no connection between T and the array element type).

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键的要求.

Also note that I have added Hashable requirement for the keys.