swift学习-元组

作者: JaneJie | 来源:发表于2015-08-07 21:12 被阅读4610次

元组

元组(tuples)把多个值组合成一个复合值。元组内的值可以使任意类型,并不要求是相同类型。


let http404Error = (404, "Not Found")
// http404Error 的类型是 (Int, String),值是 (404, "Not Found")

你可以将一个元组的内容分解(decompose)成单独的常量和变量,然后你就可以正常使
用它们了:

let (statusCode, statusMessage) =  (404, "Not Found")
 println("The status code is \(statusCode)")
// 输出 "The status code is 404"
 println("The status message is \(statusMessage)")5.
 // 输出 "The status message is Not Found"

如果你只需要一部分元组值,分解的时候可以把要忽略的部分用下划线(_)标记:

 let (justTheStatusCode, _) = (404, "Not Found")
 println("The status code is \(justTheStatusCode)")
3. // 输出 "The status code is 404"

此外,你还可以通过下标来访问元组中的单个元素,下标从零开始:

let http404Error = (404, "Not Found")

 println("The status code is \(http404Error.0)")
 // 输出 "The status code is 404"
 println("The status message is \(http404Error.1)")
 // 输出 "The status message is Not Found"

你可以在定义元组的时候给单个元素命名:

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

给元组中的元素命名后,你可以通过名字来获取这些元素的值:

 println("The status code is \(http200Status.statusCode)")
 // 输出 "The status code is 200"
 println("The status message is \(http200Status.description)")
 // 输出 "The status message is OK"

相关文章

  • swift学习-元组

    元组 元组(tuples)把多个值组合成一个复合值。元组内的值可以使任意类型,并不要求是相同类型。 你可以将一个元...

  • 5.元组(tuple)及可空类型(null_type)

    元组 kotlin_元组 swift_元组 可空类型 kotlin_可空类型 Swift可选/可空类型(Optio...

  • Swift超基础语法(元组篇)

    你对Swift中的元组了解多少呢?...很有自信嘛...看完这篇文章再说喽 元组 元组是Swift中特有的,OC中...

  • Swift 的元组是精简版结构体?骗你的啦

    Swift 的元组是精简版结构体?骗你的啦 Swift 的元组是精简版结构体?骗你的啦

  • Swift 元组

    Swift 元组 元组比较 两个相同元素类型的元组,如果每个元素都遵循了 Equatable 协议,那么这两个元组...

  • 语法进阶-元组

    ---参考Bannings的Swift 元组(Tuples)介绍 1. 元组的定义2.读取元组中的数据3.跳过不关...

  • 一个元组小技巧 & Swift与OC混编

    一个元组小技巧 ![Uploading Honzon_045208.jpg . . .]#元组小拓展用法Swift...

  • Swift学习(三)---元组Tuple

    定义 元组可以把多个值合并成单一复合类型的值元组内的值可以是任意类型例如error错误返回,我们可能需要error...

  • Swift 元组

    元组(tuples)把多个值组合成一个复合值。元组内的值可以是任意类型,并不要求是相同类型。 下面这个例子中,(4...

  • swift 元组

    //定义文具信息为元组类型var wenju = ("铅笔","橡皮","录音笔","书包","书本") //定义...

网友评论

本文标题:swift学习-元组

本文链接:https://www.haomeiwen.com/subject/zkvbqttx.html