How to access deeply nested dictionaries in Swift

后端 未结 10 894
名媛妹妹
名媛妹妹 2020-11-28 04:46

I have a pretty complex data structure in my app, which I need to manipulate. I am trying to keep track of how many types of bugs a player has in thier garden. There are te

10条回答
  •  自闭症患者
    2020-11-28 04:59

    When working with dictionaries you have to remember that a key might not exist in the dictionary. For this reason, dictionaries always return optionals. So each time you access the dictionary by key you have to unwrap at each level as follows:

    bugsDict["ladybug"]!["spotted"]!["red"]!++
    

    I presume you know about optionals, but just to be clear, use the exclamation mark if you are 100% sure the key exists in the dictionary, otherwise it's better to use the question mark:

    bugsDict["ladybug"]?["spotted"]?["red"]?++
    

    Addendum: This is the code I used for testing in playground:

    var colorsDict = [String : Int]()
    var patternsDict =  [String : [String : Int]] ()
    var bugsDict = [String : [String : [String : Int]]] ()
    
    colorsDict["red"] = 1
    patternsDict["spotted"] = colorsDict
    bugsDict["ladybug"] = patternsDict
    
    
    bugsDict["ladybug"]!["spotted"]!["red"]!++ // Prints 1
    bugsDict["ladybug"]!["spotted"]!["red"]!++ // Prints 2
    bugsDict["ladybug"]!["spotted"]!["red"]!++ // Prints 3
    bugsDict["ladybug"]!["spotted"]!["red"]! // Prints 4
    

提交回复
热议问题