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

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

提交回复
热议问题