Swift 是否有空合并运算符,如果没有,自定义运算符的示例是什么? [英] Does Swift have a null coalescing operator and if not, what is an example of a custom operator?

查看:26
本文介绍了Swift 是否有空合并运算符,如果没有,自定义运算符的示例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多语言中的一个共同特征,空合并运算符,是一种经常使用的二元运算符缩短类型的表达式:

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

x = possiblyNullValue NCO valueIfNull

...其中 NCO 是语言的空合并运算符的占位符.

…where NCO is a placeholder for the language’s null coalescing operator.

Objective C 的 Null Coalescing Operator 是 ?:,所以表达式为:

Objective C's Null Coalescing Operator is ?:, so the expression would be:

x = possiblyNullValue ?: valueIfNull

上面的表达式也等价于使用三级运算符:

The above expression is also equivalent to the use of tertiary operator:

 x =  someTestForNotNull( possiblyNullValue ) ? possiblyNullValue : valueIfNull

空合并算子的优势

  • 更易读的代码(尤其是长的、描述性的变量名称)
  • 减少排版错误的可能性(测试变量只输入一次)
  • 当测试变量是 getter 时,不会对测试变量进行双重评估,因为它访问了一次(或者需要缓存它以避免双重评估).
  • 推荐答案

    从 Swift 2.2 (Xcode 6, beta 5) 开始是 ??

    As of Swift 2.2 (Xcode 6, beta 5) it's ??

    var x: Int?
    var y: Int? = 8
    
    var z: Int = x ?? 9000
    // z == 9000
    
    z = y ?? 9001
    // z == 8
    

    <代码>一个 ??b 相当于下面的代码:

    a != nil ? a! : b
    

    从 Beta 6 开始,您可以这样做:

    And as of Beta 6, you can do this:

    x ?? y ?? 1 == 8
    

    这篇关于Swift 是否有空合并运算符,如果没有,自定义运算符的示例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆