【问题标题】:Swift issue working with complex Dictionaries使用复杂字典的 Swift 问题
【发布时间】:2021-05-01 20:39:33
【问题描述】:

我正在尝试创建一个包含以下数据的复杂字典:

let teamInfo = [teamId : [teamInit, teamLogo]]
let gameInfo = [gameId : [gameStatus : status]]
                
let temp = NSMutableDictionary(dictionary: teamInfo)
temp.addEntries(from: gameInfo)
                
complexDictionary[weekId] = temp

我正在尝试这样声明我的 complexDictionary,但有问题:

var complexDictionary = [String : [String : [String : String]], [String : [Bool : Bool]]] ()

【问题讨论】:

  • 你能提供更多关于你的“问题”的细节吗?但是,实际上,您不应该在 Swift 中使用 NSMutableDictionary。您也可能不应该使用字典中的字典。你应该使用结构。 [Bool:Bool] 的意义何在?
  • @Paulw11 你可能是对的,我还在学习说话的绳索。你能用结构来澄清你的意思吗?
  • 用谷歌搜索并不难:docs.swift.org/swift-book/LanguageGuide/…
  • 从长远来看,确实结构可能更好,但知道如何使用 Swift Dictionary(又名[AnyHashable: Any] 可能是有益的第一步developer.apple.com/documentation/swift/dictionary

标签: ios swift dictionary


【解决方案1】:
var complexDictionary = [String : [String : [String : String]], [String : [Bool : Bool]]] ()

原因:

字典文字中的预期':'

因为你在[String : [String : [String : String]]] 和[String : [Bool : Bool]] 之间添加了一个,,这是一个有效的字典类型(我猜你想要[String : [String : [Bool : Bool]]]) 你需要的是[String: Any]:

let teamInfo = ["teamId" : ["teamInit", "teamLogo"]]
let gameInfo = ["gameId" : [true : false]]

let temp = NSMutableDictionary(dictionary: teamInfo)
temp.addEntries(from: gameInfo)
                
var complexDictionary: [String : Any] = [:]

complexDictionary["weekId"] = temp // ["teamId": ["teamInit", "teamLogo"], "gameId": [1: 0]]

【讨论】:

    猜你喜欢
    • 2016-11-20
    • 2016-01-09
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    相关资源
    最近更新 更多