fengye87 fengye87 - 7 months ago 24
Swift Question

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

So I was trying to do

let foo = dict["key"] as? String ?? "empty"
var bar = some_func(string: foo!)


and XCode 6 complains that "Operand of postfix '!' should have optional type; type is 'String'" on the second line.

If I change the first line to

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


the error goes away.

Is this some kind of flaw or am I just doing something wrong?

Answer

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.)

Comments