-1

我正在尝试创建一个具有 Hashable 项和 Any 项的元组类型,并在 Dictionary 的自定义初始化程序中使用它。然而,斯威夫特不会以这种方式使用 Hashable,我被困在另一种选择中。我不想将我可以创建的字典限制为仅使用字符串作为键。

protocol CollectionInitializeable {
    associatedtype T
    init(items: [T])
}

extension Dictionary: CollectionInitializeable {

    typealias T = (Hashable, Any) // not allowed

    init(items: [T]) {

        self.init()
        // etc...
    }
}
4

1 回答 1

1

更新:

这现在是不必要的,感谢Dictionary.init(uniqueKeysWithValues:)Dictionary.init(_:uniquingKeysWith:)

原帖:

你在寻找这样的东西吗?

protocol CollectionInitializeable {
    associatedtype T
    init<C: Collection>(items: C) where C.Iterator.Element == T
}

extension Dictionary: CollectionInitializeable {
    typealias T = Iterator.Element
    
    init<C: Collection>(items c: C)
    where C.Iterator.Element == T {
        self.init()
        for (key, value) in c {
            self[key] = value
        }
    }
}

let a = [
    (key: 1, value: "a"),
    (key: 2, value: "b"),
    (key: 3, value: "c")
]

print(Dictionary(items: a))
于 2017-07-18T18:10:13.380 回答