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

后端 未结 6 2235
醉酒成梦
醉酒成梦 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:06

    What Venkat says is correct: there is none but you can define one. His implementation however is not ideal because he forgot to use @auto_closure.

    Also I believe you can overload || without needing to define a new operator.

    I do not have the compiler here, but I'll try to give you the code from memory:

    func ||| (maybe: Optional, defaultValue: @auto_closure () -> T) -> T {
        if let some = maybe { 
          return some 
        }
        return defaultValue()
    }
    

    Edit: Thanks to Martin R for testing this with the compiler. See the comments. Apparently overloading || is possible but may not work as expected because of the way Swift handles resolution of overloaded operators (which is undocumented and therefore I have no idea if it can be worked around or not). I've changed the function above to use |||.

提交回复
热议问题