赋值运算
let b = 10
var a = 5
a = b
//a现在等于10
let (x, y) = (1, 2)
//x等于1,y等于2
算数运算
1 + 2 // 3
5 - 3 // 2
2 * 3 // 6
10.0 / 2.5 // 4.0
"hello, " + "world" // "hello, world"
余数运算
9 % 4 // 1
-9 % 4 // -1
一元加减法运算
let three = 3
let minusThree = -three // -3
let plusThree = -minusThree // 3
加号没有起任何作用
let minusSix = -6
let alsoMinusSix = +minusSix // -6
混合赋值运算
var a = 1
a += 2 // 3,a=a+2
比较运算
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)
(1, "zebra") < (2, "apple") // true because 1 is less than 2; "zebra" and "apple" are not compared
(3, "apple") < (3, "bird") // true because 3 is equal to 3, and "apple" is less than "bird"
(4, "dog") == (4, "dog") // true because 4 is equal to 4, and "dog" is equal to "dog"
三元运算
let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
// rowHeight = 90
空合运算符
表达式:a??b
a为非空则返回a,否则返回默认值b,a 是optional类型,此表达式等价于:
a != nil ? a! : b
例如:
let defaultColorName = "red"
var userDefinedColorName: String? // 默认为 nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
//userDefinedColorName为空,返回"red"
userDefinedColorName = "green"
colorNameToUse = userDefinedColorName ?? defaultColorName
//userDefinedColorName不为空,返回"green"
范围运算
没有下标
for index in 10...15 {
print("\(index) times 5 is \(index * 5)")
}
// 10 times 5 is 50
// 11 times 5 is 55
// 12 times 5 is 60
// 13 times 5 is 65
// 14 times 5 is 70
需要下标
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
部分范围:
for name in names[2...] {
print(name)
}
// Brian
// Jack
for name in names[...2] {
print(name)
}
// Anna
// Alex
// Brian
for name in names[..<2] {
print(name)
}
// Anna
// Alex
let range = ...5
range.contains(7) // false
range.contains(4) // true
range.contains(-1) // true
逻辑运算
非: !a
且:a && b
或:a || b
网友评论