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"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。