您当前的位置:首页 > 计算机 > 编程开发 > Swift

Swift元组(Tuples)

时间:05-17来源:作者:点击数:

元组可以将多个数值组合成一个复合值,元组中得值可以是任意类型,并且值与值之间的类型可以不同。

在这里例子中 (404,”Not Found”)是一个描述HTTP状态码的元组。 HTTP状态码是在请求网页的时候由服务器返回的,404 Not Found表示请求的网页不存在。

let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")

(404,”Not Found”) 将 Int(数字)和String(描述)组合在一起描述HTTP的状态码。可以这么说明:(Int,String)元组类型。

你可以通过元组创建任意类型的排列,并且可以包含任意数量的不同类型,比如你可以创建 (Int,Int,Int) 或者 (String,Bool) 或者任意其他你需要的排列组合。

你也可以分解元组的内容到常量或者变量中,然后进行访问。

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"

或者使用从0开始的索引来访问某一个元组元素:

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)11)
// prints "The status message is OK"

元组在函数返回值上特别有用,一个尝试提取网页信息的函数可以返回(Int, String)元组类型来描述网页提取的成功或者失败的信息。相比于函数返回单一的类型值,返回多个类型值的函数能提供更多有用的信息。

注意:元组仅对临时的相关数据组合有用,他们并不适合于创建复杂的数据结构,如果你需要持续使用数据结构,请使用类或者结构类型而非元组类型。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门