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..

let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
    print("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值