Swift元组作为字典值

时间:2015-03-13 20:23:18

标签: ios swift xcode6

我有一个下面的类,它使用下标作为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?’ “

谁能告诉我这里做错了什么?

这是游乐场快照:

enter image description here

1 个答案:

答案 0 :(得分:2)

由于您的truthDict已定义为可选,因此您需要打开它。我没有收到与您相同的错误,但您应该尝试truthDict!["you"]或完全删除定义中的可选项。

var truthDict = STCTruthDict()

truthDict!["you"] = relationshipTuple
//       ^