簡體   English   中英

Swift 元組作為字典值

[英]Swift tuple as dictionary value

我有一個以下類,它使用下標作為其本質上圍繞 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?’ “

誰能告訴我在這里做錯了什么?

這是操場快照:

在此處輸入圖片說明

因為您的truthDict被定義為可選的,所以您需要解開它。 我沒有得到與您相同的錯誤,但您應該嘗試truthDict!["you"]或完全從定義中刪除可選項。

var truthDict = STCTruthDict()

或者

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM