Swift: Testing optionals for nil

前端 未结 14 654
攒了一身酷
攒了一身酷 2020-12-08 08:51

I\'m using Xcode 6 Beta 4. I have this weird situation where I cannot figure out how to appropriately test for optionals.

If I have an optional xyz, is the correct w

14条回答
  •  天命终不由人
    2020-12-08 09:29

    Also you can use Nil-Coalescing Operator

    The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

    let value = optionalValue ?? defaultValue
    

    If optionalValue is nil, it automatically assigns value to defaultValue

提交回复
热议问题