× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to access deeply nested dictionaries in Swift

Antonio Bello
Mar 01, 2015
<p>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:</p> <pre><code>bugsDict["ladybug"]!["spotted"]!["red"]!++ </code></pre> <p>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:</p> <pre><code>bugsDict["ladybug"]?["spotted"]?["red"]?++ </code></pre> <p><strong>Addendum</strong>: This is the code I used for testing in playground:</p> <pre><code>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 </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/25475463/How%20to%20access%20deeply%20nested%20dictionaries%20in%20Swift/25475702">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus