Antonio Santos Antonio Santos - 2 months ago 5x
Swift Question

Why is the word "Optional" being added when I print a string using a dictionary entry as the variable?

I am learning Swift and hacking around in a playground. I have the following Dictionary:

var person = [
"first": "John",
"last": "Smith",
"age": 21

I am using the following line to print output:

"Your first name is \(person["first"]) and you are \(person["age"]) years old."

With this code, I get the following output:

// -> "Your first name is Optional(John) and you are Optional(21) years old."

I expected to receive the following as output:

// -> "Your first name is John and you are 21 years old."

Where is the Optional coming from? Why doesn't this simply print the value at the specified key? What do I need to do to fix this?


Retrieving a value for a given key from a dictionary is always an optional because the key might not exist then the value is nil. Using String Interpolation "\(...)" the Optional is included as literal string.

To avoid the literal Optional(...) in String Interpolation you have to unwrap the optionals preferred in a safe way

if let first = person["first"] as? String, age = person["age"] as? Int {
   print("Your first name is \(first) and you are \(age) years old.")