Dictionaries
8 min · Swift
Store values under named keys instead of numbered positions.
Enemy 1 of 5
An Array is great when order matters and you look things up by position. Often, though, you want to find something by a meaningful name instead — a player's username, a product's ID, a word you're counting occurrences of. That's what a Dictionary is for: it stores key-value pairs written as [key: value], and lets you retrieve a value quickly given its key rather than its position.
Looking a value up uses square brackets with the key instead of a numeric position: player["name"]. Because a key you ask for might not actually exist in the dictionary, Swift wraps the result in an Optional — a value that's either something or explicitly nothing (nil) — rather than assuming success. The ! after the lookup (player["name"]!) force-unwraps it, telling Swift "I'm confident this key exists, just give me the value directly." This is convenient for learning and quick scripts, but force-unwrapping a key that turns out to be missing crashes the program immediately, so production Swift code usually handles the nil case explicitly instead (with patterns you'll meet later, like if let).
Loading editor...