您的位置:首页 > 移动开发 > Swift

Swift学习之六:元组(Tuples)

2016-08-23 16:08 316 查看
元组是多个值组合而成的复合值。元组中的值可以是任意类型,而且每一个元素的类型可以是不同的。

如:

[objc] view
plain copy

 print?





// http404Error是(Int, String)类型  

// 这个元组是二元组,是一个整型和字符串类型的组合,这里代表着404的意思是Not Found  

let http404Error = (404, "Not Found")  

元组是可以分解的。

如:

[objc] view
plain copy

 print?





let (statusCode, statusMessage) = http404Error  

// prints "The status code is 404"  

println("The status code is \(statusCode)")  

println("The status message is \(statusMessage)")  

元组在分解时,可以只分解部分值,而忽略其它值,忽略其它值可以用下划线_来代替.

如:

[objc] view
plain copy

 print?





let (statusCode, _) = http404Error  

println("The status code is \(statusCode)")  

访问元组的另外一种方式:通过下标获取,从0开始

如:

[objc] view
plain copy

 print?





let http404Error = (404, "Not Found")  

// 通过元组.0获取第二个值  

println("The status code is \(http404Error.0)")  

// 通过元组.1获取第二个值  

println("The status message is \(http404Error.1)")  

访问元组元素还有一种方式:给定元组元素命名,然后通过名称获取值(元组.名称)

如:

[objc] view
plain copy

 print?





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

println("The status code is \(http200Status.statusCode)")  

println("The status message is \(http200Status.description)")
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: