Swift学习——Swift基础详解(五)

上回书说道:灰常灰常基本的数据类型

下面咱们来点高级的:


Tuples    元组

元组存储一对键值,并且没有类型限制

let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")
书上废话一堆,反正元组就是这么写,上面的例子还是(Int,String)类型的元组,而且元组里面的类型随便你定义

也可以将元组的变量分离:

let (statusCode, statusMessage) = http404Error
println("The status code is \(statusCode)")
// prints "The status code is 404"
println("The status message is \(statusMessage)")
// prints "The status message is Not Found
如果你只需要元组中的部分值,可以使用下划线将不需要的值代替:

let (justTheStatusCode, _) = http404Error
println("The status code is \(justTheStatusCode)")
// prints "The status code is 404
也可以使用索引获取元组中的值:

println("The status code is \(http404Error.0)")
// prints "The status code is 404"
println("The status message is \(http404Error.1)")
// prints "The status message is Not Found
在元组定义的时候,可以命名元组中的值,这样就可以用值的名称获取值了:

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

println("The status code is \(http200Status.statusCode)")
// prints "The status code is 200"
println("The status message is \(http200Status.description)")
// prints "The status message is OK
对了,元组的一个非常有用的地方就是它可以作为函数的返回值,在之前的文章介绍过,Swift中的函数可以有多个返回值。

还有就是,元组不适合复杂的数据组合,如果数据太复杂,还是使用类或者结构体吧。




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值