使用字典时,必须记住字典中可能不存在键。因此,字典总是返回可选内容。因此,每次您通过按键访问字典时,都必须按照以下步骤在每个级别上展开包装:
bugsDict["ladybug"]!["spotted"]!["red"]!++
我假设您了解可选内容,但为了清楚起见,如果您100%确信字典中存在键,请使用感叹号,否则最好使用问号:
bugsDict["ladybug"]?["spotted"]?["red"]?++
附录 :这是我在操场上测试的代码:
var colorsDict = [String : Int]()var patternsDict = [String : [String : Int]] ()var bugsDict = [String : [String : [String : Int]]] ()colorsDict["red"] = 1patternsDict["spotted"] = colorsDictbugsDict["ladybug"] = patternsDictbugsDict["ladybug"]!["spotted"]!["red"]!++ // Prints 1bugsDict["ladybug"]!["spotted"]!["red"]!++ // Prints 2bugsDict["ladybug"]!["spotted"]!["red"]!++ // Prints 3bugsDict["ladybug"]!["spotted"]!["red"]! // Prints 4



