各种编程语言的运算符、条件语句、循环语句大同小异
运算符
可参考 JS 的说明:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators
注意运算符的优先级
算术运算符
算术运算符包括:+ - * / % ,但不包括: ++ --
比较运算符
比较运算符包括:> >= < <= == != === !==
逻辑运算符
逻辑运算符包括:&& || ! !!
位运算符
位运算符包括:& | ^ ~ << >> >>>
/* Objective-C 左移枚举 */typedef NS_ENUM (NSInteger, DirectionType) {DirectionTypeLeft = 1 << 1,DirectionTypeRight = 1 << 2,DirectionTypeUp = 1 << 3,DirectionTypeDown = 1 << 4};DirectionType type = DirectionTypeLeft | DirectionTypeRight;NSLog(@"%ld", type & DirectionTypeLeft); // 2NSLog(@"%ld", type & DirectionTypeRight); // 4NSLog(@"%ld", type & DirectionTypeUp); // 0NSLog(@"%ld", type & DirectionTypeDown); // 0
/* Swift 左移枚举 */struct Direction: OptionSet {let rawValue: Intstatic let Left = Direction(rawValue: 1 << 1)static let Right = Direction(rawValue: 1 << 2)static let Up = Direction(rawValue: 1 << 3)static let Down = Direction(rawValue: 1 << 4)}let direction: Direction = [.Left, .Up]print(direction.contains(.Left)) // trueprint(direction.contains(.Right)) // falseprint(direction.contains(.Up)) // trueprint(direction.contains(.Down)) // false
赋值运算符
赋值运算符包括:= += -= 等,也就是 “算术运算符”、”位运算符 与 “等号” 的组合
区间运算符
x...y 即 [x, y] x..<y 即 [x, y)
for i in 1...5 {print(i)}
条件语句
if - else if - else
let score = 70if score < 60 {print("不及格")} else if (score >= 60 && score <= 80) {print("良好")} else {print("优秀")}
switch - case - break
var index = 10switch index {case 100:print( "index 的值为 100")break // 在 Swift 的 switch 语句中,break 默认隐式添加到 case 语句末尾,所以不必再添加了。case 10, 15:print( "index 的值为 10 或 15")fallthrough // 如果使用了fallthrough 语句,则会继续执行之后的 case 或 default 语句,不论条件是否满足都会执行。case 5: do {print( "index 的值为 5")} // 大语句块,使用 `do { /* code... */ }` 包裹breakdefault:print( "默认 case")break}/*输出:index 的值为 10 或 15index 的值为 5*/
? : ??
Exp1 ? Exp2 : Exp3
- 如果
Exp1为真,则执行Exp2 - 如果
Exp1为假,则执行Exp3
var age = 20var isAdult = age >= 18 ? "成年人" : "未成年"print(isAdult)
Value ?? DefaultValue
- 如果
Value不为nil,则返回Value值本身 - 如果
Value为nil,则返回DefaultValue默认值
var name: String?var thisName = name ?? "佚名"print(thisName)
循环语句
for element in collection {statement}
while condition {statement}
repeat {statement} while condition
九九乘法表
for i in 1...9 {for j in 1...i {print("\(j) x \(i) = \(i * j)", terminator: "\t")}print("")}
1 x 1 = 11 x 2 = 2 2 x 2 = 41 x 3 = 3 2 x 3 = 6 3 x 3 = 91 x 4 = 4 2 x 4 = 8 3 x 4 = 12 4 x 4 = 161 x 5 = 5 2 x 5 = 10 3 x 5 = 15 4 x 5 = 20 5 x 5 = 251 x 6 = 6 2 x 6 = 12 3 x 6 = 18 4 x 6 = 24 5 x 6 = 30 6 x 6 = 361 x 7 = 7 2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 5 x 7 = 35 6 x 7 = 42 7 x 7 = 491 x 8 = 8 2 x 8 = 16 3 x 8 = 24 4 x 8 = 32 5 x 8 = 40 6 x 8 = 48 7 x 8 = 56 8 x 8 = 641 x 9 = 9 2 x 9 = 18 3 x 9 = 27 4 x 9 = 36 5 x 9 = 45 6 x 9 = 54 7 x 9 = 63 8 x 9 = 72 9 x 9 = 81

