Swift--基础(二)元组 断言 错误处理

元组(tuples

把多个值组合成一个复合值。元组内的值可以是任意类型,并不要求是相同类型

let http404Error = (404, "Not Found")

let (statusCode, statusMessage) = http404Error

print("The status code is (statusCode)")

print("The status message is (statusMessage)")

忽略后面的值

let (justTheStatusCode, _) = http404Error 

print("The status code is (justTheStatusCode)")

通过下标来访问元组中的单个元素

print("The status code is (http404Error.0)")

可以在定义元组的时候给单个元素命名

let http200Status = (statusCode: 200, description: "OK")

print("The status code is (http200Status.statusCode)")

断言

let age = -3

assert(age >= 0, "A person's age cannot be less than zero")

会导致程序的终止

错误处理

func makeASandwich() throws {

    // ...

}

do {

    try makeASandwich()

    eatASandwich()

} catch SandwichError.outOfCleanDishes {

    washDishes()

} catch SandwichError.missingIngredients(let ingredients) {

    buyGroceries(ingredients)

}

原文地址:https://www.cnblogs.com/huoran1120/p/6121911.html