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

元组(tuplesless

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

let http404Error = (404, "Not Found")code

let (statusCode, statusMessage) = http404Errorip

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

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

忽略后面的值程序

let (justTheStatusCode, _) = http404Error 命名

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

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

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)

}

相关文章
相关标签/搜索