Swift 元组作为字典值
Swift tuple as dictionary value
我有以下 class,它使用下标作为其本质上对 Swift 字典的包装。
class STCTruthDict: NSObject, SequenceType {
typealias IpRelationshipTuple = (String, String?)
private var truthDict: [String : IpRelationshipTuple] = [ : ]
subscript(key: String) -> IpRelationshipTuple? {
get {
return self.truthDict[key]
}
set {
truthDict[key] = newValue
}
}
// MARK: - Initializers
override init() {
super.init()
}
func generate() -> DictionaryGenerator <String, IpRelationshipTuple> {
return self.truthDict.generate()
}
}
我正在尝试通过以下代码使用此 class 及其来自另一个 class 的下标:
private var truthDict: STCTruthDict?
.....
.....
.....
// Get ip and userId
let ipToBeAdded = responseData["ip"] as! String
let userIdForIP = responseData["user_id"] as! String
// update truth table
let relationshipTuple = (ipToBeAdded, nil) as STCTruthDict.IpRelationshipTuple?
self.truthDict[userIdForIP] = relationshipTuple
但我收到一条错误消息:
“Cannot assign to immutable value of type ‘IpRelationshipTuple?’ “
谁能告诉我我做错了什么?
这是游乐场快照:
因为您的 truthDict
被定义为可选的,您需要将其解包。我没有得到与你相同的错误,但你应该尝试 truthDict!["you"]
或从定义中完全删除可选。
var truthDict = STCTruthDict()
或
truthDict!["you"] = relationshipTuple
// ^
我有以下 class,它使用下标作为其本质上对 Swift 字典的包装。
class STCTruthDict: NSObject, SequenceType {
typealias IpRelationshipTuple = (String, String?)
private var truthDict: [String : IpRelationshipTuple] = [ : ]
subscript(key: String) -> IpRelationshipTuple? {
get {
return self.truthDict[key]
}
set {
truthDict[key] = newValue
}
}
// MARK: - Initializers
override init() {
super.init()
}
func generate() -> DictionaryGenerator <String, IpRelationshipTuple> {
return self.truthDict.generate()
}
}
我正在尝试通过以下代码使用此 class 及其来自另一个 class 的下标:
private var truthDict: STCTruthDict?
.....
.....
.....
// Get ip and userId
let ipToBeAdded = responseData["ip"] as! String
let userIdForIP = responseData["user_id"] as! String
// update truth table
let relationshipTuple = (ipToBeAdded, nil) as STCTruthDict.IpRelationshipTuple?
self.truthDict[userIdForIP] = relationshipTuple
但我收到一条错误消息:
“Cannot assign to immutable value of type ‘IpRelationshipTuple?’ “
谁能告诉我我做错了什么?
这是游乐场快照:
因为您的 truthDict
被定义为可选的,您需要将其解包。我没有得到与你相同的错误,但你应该尝试 truthDict!["you"]
或从定义中完全删除可选。
var truthDict = STCTruthDict()
或
truthDict!["you"] = relationshipTuple
// ^