Question about optional syntax

Hello, total Swift beginner here...

Would anyone be so kind as to quickly explain what's going on in the allowedMessage declaration? I've been looking at different resources to try and figure it out but I am still confused.

Any help would be greatly appreciated. Thanks.

The ?: thing is called a ternary operator, and it exists in many languages if you want to google it. It isn't related to optionals necessarily. I think of the ternary operator as a shorthand for an if statement.

Essentially, if the condition evaluates to true, then the part after the ? is used. Otherwise, the part after the : is used.

Using your example above, the declaration is equivalent to the following code:

let allowedMessage: String?

if age >= 21 {
    allowedMessage = "Welcome!"
} else {
    allowedMessage = nil
}

Separately, I would note that the code snippet has a rather serious error in that if the age is less than 21, the app will crash on the third line, as the allowedMessage variable will be equal to nil and therefore the allowedMessage! unwrap will throw a fatal error. It also introduces a nonsense temporary optional variable for the 'happy path'. If the intent is to stop execution if age is less than 21, a better formation would be:

guard age >= 21 else { fatalError("Too young") }

let allowedMessage = "Welcome!"

5 Likes

Thank you so much Benjamin. I really, really appreciate this. :smiley:

Hope you're having a great day.

Terms of Service

Privacy Policy

Cookie Policy