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

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

    (Also see blog post)

    No, Swift doesn't currently support a null coalescing operator.

    Defining Custom Null Coalescing Operator for Swift

    A custom operator can be defined for Swift, with the following considerations regarding the Swift language:

    Swift and Nil

    Swift supports a null concept through its Optional type (a Discriminated Union of sorts) which either holds a value of the underlying type or no value (indicated by nil) and must be explicitly defined as being optional:

    var a : String?
    

    A non-optional type can never be nil, or assigned nil. Therefore a custom infix binary NCO can be expected to take an optional as its first parameter.

    Available Characters for Custom Operators in Swift

    In Swift, custom operators can be comprised of the following characters only:

    / = - + * % < > ! & | ^ . ~
    

    The Operator

    Given the choice of available characters, ||| (three pipes, no spacing) isn't terrible (similar to the double pipe OR in Javascript which is used like a NCO):

    Using the Operator

    var a = String?
    var z = a ||| "it's nil!"
    println(z) //Output: it's nil!
    

    Defining the Operator

    operator infix ||| {}
    
    @infix func ||| (left: T?, right: T) -> T  {
      if let l = left { return l }
      return right
    }
    

提交回复
热议问题