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

前端 未结 2 974
忘掉有多难
忘掉有多难 2021-02-01 02:05

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

相关标签:
2条回答
  • 2021-02-01 02:21

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

    0 讨论(0)
  • 2021-02-01 02:42

    Your foo will be a String not a String? because the nil coalescing operator ?? will either unwrap your conditional cast if it is .some (resulting in a String) or it will use "empty", which is also a String.

    0 讨论(0)
提交回复
热议问题