Swift中的Tuple类型可以包含任何值,并且这些值的类型可以互相不一样。Tuple本身比较简单,需要记得也就是访问Tuple的方式。
使用变量名访问
let http404Error = (404, "Not Found") // http404Error is of type (Int, String), and equals (404, "Not Found") let (statusCode, statusMessage) = http404Error //注意这里 print("The status code is \(statusCode)") // Prints "The status code is 404" print("The status message is \(statusMessage)") // Prints "The status message is Not Found"
使用这种方式,还可以使用_忽略后面的Tuple值:
let (justTheStatusCode, _) = http404Error print("The status code is \(justTheStatusCode)") // Prints "The status code is 404"
使用序号访问
print("The status code is \(http404Error.0)") // Prints "The status code is 404" print("The status message is \(http404Error.1)") // Prints "The status message is Not Found"
使用key访问
Tuple定义的时候,可以给每个value前添加一个key,访问的时候可以使用这个key访问:
let http200Status = (statusCode: 200, description: "OK") print("The status code is \(http200Status.statusCode)") // Prints "The status code is 200" print("The status message is \(http200Status.description)") // Prints "The status message is OK"