So I was trying to do
let foo = dict[\"key\"] as? String ?? \"empty\"
var bar = some_func(string: foo!)
and XCode 6 complains that
Op
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.)