swift入门1 操作符

注:英文部分来自官方文档

基础操作符

赋值操作符

If the right side of the assignment is a tuple with multiple values, its elements can be decomposed into multiple constants or variables at once:
如果赋值的左边是一个包含多个值的tuple,它的元素可以一次解析为多个常量或变量

let (x, y) = (1, 2)
// x 等于 1, y等于 2

Unlike the assignment operator in C and Objective-C, the assignment operator in Swift does not itself return a value. The following statement is not valid:

和c oc中的赋值操作符不一样,swift中的赋值操作赋本身并不返回一个值。下面的程序是无效的:

if x = y {
    //无效, x = y 并不返回值.
}

nil聚合运算符 Nil-Coalescing

The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

nil聚合运算符(a ?? b) 表示:如果a包含一个值,则解析可选a;如果a为nil,则返回默认值b。 此表达式是一个可选(optional)类型。表达式b必须与a内部存储的类型一致。

The nil-coalescing operator is shorthand for the code below:
nil聚合运算符 是下面代码的简写:
a != nil ? a! : b

范围操作符 Range Operators

  • 闭合范围操作符 Closed Range Operator

The closed range operator (a...b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.

闭合范围操作符 (a...b) 定义了一个 从a到b的范围(注意中间是三点),而且包含值a和b。a的值必须必b的值大。

闭合操作符在for-in循环中特别有用:

for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
  • 半开范围操作符 Half-Open Range Operator

The half-open range operator (a..

半开范围操作符(a..

let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..

如果你觉得文章不错,可以给我打赏点比特股(bts),以示支持。_

BTS6jUaVVkz9gN8t9sWY9NR5UbiubSz7QtVDnEtFGpujYeqQSfQ5E

你可能感兴趣的:(swift入门1 操作符)