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

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

    hope this will help you

    1. yes , Now it is added in swift

    2. little Explanation

             var anumber:Int? = someValue
             var banumber = 2
             anumber =   ( anumber != nil) ? anumber : banumber ------- (a)
             println(anumber!)
      

    now instead of writing all (a) this we can just use this ->

            anumber = anumber ?? banumber
    

    and

    The operator can also be used multiple times in the same expression. like

         firstNumber ?? secondNumber ?? thirdNumber. 
    

提交回复
热议问题