Swift: Accessing Values

Accessing Values of Swift’s Dictionary:

We’ve seen how to manipulate our dictionary and how to print it out in its entirety, but what if we only want to access a single key-value pair of Swift’s dictionary?

After all, we shouldn’t have to look up a single definition in a dictionary (or scroll through all of our contacts to find a single phone number).

We can use subscript syntax to get the specific value associated with a key. Let’s say we had the following vegetableNames in our dictionary:

var vegetableNames = [
  "Potato": "Solanum tubersum",
  "Tomato": "Lycopersican esculentum",
  "Onion": "Allium cepa"
];

Our code would look like this if we wanted to extract the value associated with the key "Tomato" and assign it to a new variable called tomatoScientific:

var tomatoScientific = vegetableNames["Tomato"];

We would get the following output if we tried to print the value of (tomatoScientific):

Optional("Lycopersican esculentum")

Swift returns a value that is optional. When a value might not exist, Swift uses the optional type. We might be trying to access a key that doesn’t exist in dictionaries, so we get an optional instead of the exact value as a precaution.

Values can extract from optionals using one of two methods.

We can use an iflet statement if we aren’t sure if a key exists within a dictionary:

if let tomatoScientific = vegetableNames["Tomato"] {
  print(tomatoScientific);
} else {
  print("This key isn't present.");
}

iflet statements are used to determine whether or not a real value exists within an optional. The optional will unwrap and assign to a variable if the value exists.

We can add ! if we are absolutely certain a key exists within a dictionary, at the end of the statement, something like this:

var tomatoScientific = vegetableNames["Tomato"]! ;

Using ! forces the compiler to unwrap an optional value and interpret it as the appropriate data type; however, it should be noted that using ! on a value that does not exist can result in errors.

Swift’s Language Guide has more information on unwrapping optionals.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: