Does Swift have a null coalescing operator and if not, what is an example of a custom operator?

后端 未结 6 2237
醉酒成梦
醉酒成梦 2020-12-09 14:24

A common feature in many languages, the Null Coalescing Operator, is a binary operator often used to shorten expressions of the type:

x = possiblyNullValue N         


        
6条回答
  •  忘掉有多难
    2020-12-09 15:24

    I blogged about a custom operator function that provides nil-coalescing here: http://ijoshsmith.com/2014/07/24/nil-coalescing-operator-in-swift/

    My choice of operator was !! which combines the logical not operator (!) and the unwrap operator (!) for a "if cannot unwrap" semantic. Seems I was late to the party, given this thread is already over a month old. Either way, here's my implementation in case you're interested...

    operator infix !! {}
    
    @infix func !!  (
        value: T?,
        defaultValue: @auto_closure () -> T)
        -> T
    {
        return value ? value! : defaultValue()
    }
    

提交回复
热议问题