Chen Li Yong Chen Li Yong - 11 months ago 34
Swift Question

How to get value from optional variable, and get default value instead if the optional variable is not valid?

I have code like this that I frequently use:

var myName = "Guest"
if let data = dictionary["name"] as? String { myName = data; }
func supply (name: myName)

How to make it like this (or similar):

guard let myName = dictionary["name"] as? String else { let myName = "Guest" }
func supply (name: myName)

I prefer the latter because it involves less variable names and also more straightforward. I have tried the code, but it looks like the
let myName = "Guest"
inside the brackets is limited by the variable scope inside the brackets only. How to make it possible? Thanks.

Answer Source

Use a nil-coalescing operator.

let myName = (dictionary["name"] as? String) ?? "Guest"

This will try to unwrap the value for key "name" as string and fall back to "Guest" in the event there is no value for key "name" or if the value cannot be cast as String