Welcome to Swift (苹果官方Swift文档初译与注解十六)---101~107页(第二章)

Unary Minus Operator (一元负号操作符)

  数值的符号可以通过使用前缀-来切换,(-)称为一元负号操作符.

    let three = 3

    let minusThree = -three       // minusThree equals -3

    let plusThree = -minusThree   // plusThree equals 3, or "minus minus three

  一元符号操作符(-)直接写在要切换数值的前面,中间没有空格.

Unary Plus Operator (一元正号操作符)

  一元正号操作符(+)只是简单的返回操作值本身,没有任何改变:

    let minusSix = -6

    let alsoMinusSix = +minusSix  // alsoMinusSix equals -6

  尽管一元正号操作符并没有做任何实际事情,但是中代码中,它可以保持一个正数同一个负数可读的对称性.

Compound Assignment Operators (复合赋值操作符)

  像C语言一样,Swift提供了复合赋值操作符,下面的例子是复合加法操作符(+=):

    var a = 1

    a += 2

    // a is now equal to 3

  表达式 a += 2是a = a + 2 的缩写.实际中是加法和赋值组合为一个操作来执行.

  注意点:

  复合赋值操作符没有返回值.例如你不可以在代码中写:let b = a + = 2,这与自增和自减操作是不同的.

Comparison Operators (比较操作符)

  在Swift中,支持所有标准C的比较操作:

    Equal to (a == b)   // 等于

    Not equal to (a != b) // 不等于

    Greater than (a > b) // 大于

    Less than (a < b) // 小于

    Greater than or equal to (a >= b) // 大于等于

    Less than or equal to (a <= b) // 小于等于

  注意点:

  Swift另外提供了两个用操作符( ===和 !== )来检测是否两个对象引用都指向相同的一个对象实例.

  每个比较操作符返回一个Bool类型的值来表示结果是true或者不是:

    1 == 1   // true, because 1 is equal to 1

    2 != 1   // true, because 2 is not equal to 1

    2 > 1    // true, because 2 is greater than 1

    1 < 2    // true, because 1 is less than 2

    1 >= 1   // true, because 1 is greater than or equal to 1

    2 <= 1   // false, because 2 is not less than or equal to 1

  比较操作符通常用在条件判断语句,例如if语句:

    let name = "world"

    if name == "world" {

        println("hello, world")

    } else {

        println("I'm sorry (name), but I don't recognize you")

    }

    // prints "hello, world", because name is indeed equal to "world”

Ternary Conditional Operator (三元条件操作符)

  三元条件操作符是针对三个部分的特殊操作,它写为:question ? answer1 : answer2.它是一个关于question是true或false的升级版的缩写.如果question是true,它计算answer1并  且返回answer1的值;否则,它计算answer2,并返回answer2的值.

  三元条件操作符是下面代码的一个缩写版:

    if question {

        answer1

    } else {

        answer2

    }

  下面的代码样例,计算表格一行的像素行高.如果有表头,那么行高是内容的像素高再加50,如果没有表头,那么行高是内容的像素高度加20:

    let contentHeight = 40

    let hasHeader = true

    let rowHeight = contentHeight + (hasHeader ? 50 : 20)

    // rowHeight is equal to 90

  上面的代码,也可以用下面的代码处理:

    let contentHeight = 40

    let hasHeader = true

    var rowHeight = contentHeight

    if hasHeader {

        rowHeight = rowHeight + 50

    } else {

        rowHeight = rowHeight + 20

    }

    // rowHeight is equal to 90

  第一个代码样例中,使用三目条件操作符可以通过一行代码给rowHeight正确的赋值.它比第二个代码更加精简准确,去除了不必要的将rowHeight转为一个变量过程,因为在if语句中,它  的值不需要修改.

  三目条件操作符有效的减少了两个表达式判断方式.但还是要谨慎的使用三目条件操作符,否则会导致代码可读性差.尽量避免在三目条件操作中使用多个实例的复杂语句.

原文地址:https://www.cnblogs.com/caios/p/3802873.html