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

前端 未结 2 973
忘掉有多难
忘掉有多难 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.)

提交回复
热议问题