Swift optional variable assignment with default value (double question marks)

The nil-coalescing operator a ?? b is a shortcut for

a != nil ? a! : b

it returns either the left operand unwrapped or the right operand. So the type of foo is String and the second line should be

var bar = some_func(string: foo)

without the exclamation mark because foo is not an optional and can’t be unwrapped.

(If you change the first line to

let foo: String? = dict["key"] as? String ?? "empty"

then the result of the right hand side is wrapped into an optional string again, and needs
to be unwrapped in the second line. It makes the error go away, but this is probably not what you want.)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)