简体   繁体   中英

Swift tuple as dictionary value

I have a following class which uses subscripts as its essentially a wrapper around Swift dictionary.

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()
}

}

I am trying to use this class and its subscripts from another class with following code:

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

But I get an error saying:

“Cannot assign to immutable value of type ‘IpRelationshipTuple?’ “

Can anyone tell what am I doing wrong here?

This is the playground snapshot:

在此处输入图片说明

Because your truthDict is defined optional, you'll need to unwrap it. I don't get the same error as you, but you should try truthDict!["you"] or remove the optional from the definition altogether.

var truthDict = STCTruthDict()

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM