我正在尝试将两个不同的泛型类型放入集合中。在此示例中,有两个数组,一个包含Int
s ,另一个包含String
s。
let intArray = Array<Int>()
let stringArray = Array<String>()
let dict = [1:intArray, "one": stringArray]
错误显示表达式类型不明确,没有更多上下文。
所以我尝试指定Dictionary
的类型
let dict: [Hashable: Any] = [1:intArray, "one": stringArray]
这导致两个错误。
添加import Foundation
和使用NSDictionary
作为类型工作正常。
let dict: NSDictionary = [1:intArray, "one": stringArray]
但这也可以在不使用Foundation的情况下在纯Swift中实现。Dictionary
必须具有的类型是什么?
编辑:这显然与键的类型有关。它们必须具有相同的类型,而不仅仅是符合Hashable
。
let dict: [Int:Any] = [1:intArray, 2: stringArray]
这有效。但是有可能使值的类型更精确吗?[Int:Array<Any>]
不起作用。
详细说明@RobNapier的答案,这是一种enum
用于字典的键和值的类似方法:
enum Key: Equatable, Hashable {
case IntKey(Int)
case StringKey(String)
var hashValue: Int {
switch self {
case .IntKey(let value) : return 0.hashValue ^ value.hashValue
case .StringKey(let value) : return 1.hashValue ^ value.hashValue
}
}
init(_ value: Int) { self = .IntKey(value) }
init(_ value: String) { self = .StringKey(value) }
}
func == (lhs: Key, rhs: Key) -> Bool {
switch (lhs, rhs) {
case (.IntKey(let lhsValue), .IntKey(let rhsValue)) : return lhsValue == rhsValue
case (.StringKey(let lhsValue), .StringKey(let rhsValue)) : return lhsValue == rhsValue
default: return false
}
}
enum Value {
case IntValue(Int)
case StringValue(String)
init(_ value: Int) { self = .IntValue(value) }
init(_ value: String) { self = .StringValue(value) }
}
var dict = [Key: Value]()
dict[Key(1)] = Value("One")
dict[Key(2)] = Value(2)
dict[Key("Three")] = Value("Three")
dict[Key("Four")] = Value(4)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句