我有一个下面的类,它使用下标作为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()
}
}
我正在尝试使用此类及其来自其他类的下标代码:
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?’ “
谁能告诉我这里做错了什么?
这是游乐场快照:
答案 0 :(得分:2)
由于您的truthDict
已定义为可选,因此您需要打开它。我没有收到与您相同的错误,但您应该尝试truthDict!["you"]
或完全删除定义中的可选项。
var truthDict = STCTruthDict()
或
truthDict!["you"] = relationshipTuple
// ^