控制流

// **************Control Flow***********
// For-In Loops:
// 遍历数组, 字典
let names = ["Anna", "Alex"]
for name in names {
    print("Hello, \(name)")
}

let numberOFLegs = ["spider": 8, "ant": 6]
for (animalName, legCount) in numberOFLegs {
    print("\(animalName) have \(legCount) legs")
}

// 如果没有参数,就用 下划线代替
let base   = 3
let power  = 10
var answer = 1
// ... 代表开区间, ..< 代表左开右闭区间
for _ in 1...power {
    answer *= base
}

// 添加遍历间隔 输出0,5, 10, 15 。。。。55
let minutes        = 60
let minuteInterval = 5
for trickMark in stride(from: 0, to: minutes, by: 5) {
    print("\(trickMark)")
}

//输出到60, through两边都包括, to 左开右闭
for trickMark in stride(from: 0, through: minutes, by: 5) {
    print("\(trickMark)")
}
//**********************************************
/* While loops 无太大变化
    repeat {
        statements
    } while condition
    相当于do。。while
*/


/* **********************************************
 Switch
 不用写break,但是case的body不能为空
 */
 //可以区间匹配
let approximateCount = 62
switch  approximateCount {
    case 0:
        print("\(approximateCount)")
    case 1..<5:
        print("\(approximateCount)")
    default:
        print("\(approximateCount)")
}

// 使用元组来匹配多值变量,如判断坐标点
let somePoint = (1,1)
switch somePoint {
    case (0, 0):
        print(somePoint)
    case (_, 0):
        print(somePoint)
    default:
        print(somePoint )
}

// 值绑定, 将1,和-1的值赋值给临时变量,x,y的值会变为1,-1
let point = (1, -1)
switch point {
case let(x, y) where x == y:
    print("\(x), \(y) is on the line x== y")
case let(x, y):
    print("\(x), \(y) is just some arbitarary point")
}

// 几个不同的值可以放在同一个case, 比如狗,猫都属于动物. 也可以使用值绑定
let object = "dog"
switch object {
    case "dog", "cat", "pig":
        print("\(object) is an animal")
    default:
        print("\(object)")
}

/* **********************************************
 Control Transfer Statement
 break, continue, fallthrough, return , throw
 throw用于错误处理
 return用于函数
 fallthrough 直接执行下一个case,无论符不符合条件
 */


// Labeled Statements
// guard 和 if 类似 else只在条件为false时执行 让代码结构更清晰

// Checking API Availability
// Swift支持检查API的可用性,可以确保在正确的版本用正确的API
// #available关键字
// if #available(platform name version, .., *){
//      使用version APIs on platform
// }else{
//      使用version以前的APi
// }
if #available(iOS 10, macOS 10.12 ,*) {
    // 使用iOS 10 APIs on iOS, 使用macOS 10.12 APIs on macOS
} else{
    //使用ios10,和10.12以前的APi
}

你可能感兴趣的:(控制流)