【学习】重学Swift5-运算符&流程控制


二、运算符和表达式

+ - * \ = 
// 溢出
&+  &-  &*

// 合并空值运算符
a??b // a必须是一个可选类型。b必须与a的储存类型相同 与(a = nil ? a! : b)相同

// 区间运算符
a...b // 闭区间运算符 从a到b 包含ab
a..>  左移、右移运算符 左移翻倍,右移减半
*/

// 运算符重载

三、流程控制

  1. for-in

    for i in 0..3 {
      
    }
    
    for c in "hello world" {
      
    }
    
    let names = ["zhangsan", "lisi", "wangwu"]
    for name in names {
      
    }
    
    let numberOfLegs = ["spider" : 8, "ant" : 6, "cat" : 4]
    for (animal, legs) in numberOfLegs {
        print("\(animal) have \(legs) legs")
    }
    
    for t in numberOfLegs {
        print(t.0, t.1)
    }
    
    for _ in 1...5 {
      anser *= 4
    }
    
    // 分段
    let minuteInterval = 5
    for ticket in stride(from: 0, to: 50, by: minuteInterval) {
        print(ticket)
    }
    for ticket in stride(from: 0, through: 50, by: minuteInterval) {
        print(ticket)
    }
    
  2. while

    var count = 0
    repeat {
        print(count)
        count += 1
    } while count < 5
    
  3. switch

    // swift中 switch语句必须包含全部内容,并且没有隐式贯穿
    // swift case中可以匹配多个值,写成多行,只需用逗号隔开  case "a","A":
    // swift中case还可以进行区间匹配 case 1..<5:
    // swift中case还可以进行元组匹配
    // swift中case还可以进行值绑定 case (let x, 0):
    // swift中case还可以进行where检查  case let(x,y) where x == y:
    
  4. 控制转移

    // continue
    // break
    // fallthrough 可以实现oc switvh中的隐式贯穿
    // return
    // throw
    
    // 语句标签
    
  5. guard

    guard true else {
        print("when false do something")
    }
    
    print("when true do something")
    
  6. 检查API可用性

    if #available(iOS 10, macOS10.12, *) {
        
    } else {
        
    }
    

相关