Swift基础语法简介(二)——元组

  元组把多个值合并成单一的复合型的值。元组内的值可以是任何类型,而且可以不必是同一类型。

  元组是关系数据库中的基本概念,关系是一张表,表中的每行(即数据库中的每条记录)就是一个元组,每列就是一个属性。在二维表里,元组也成为行。

  例如,(404, “Not Found”)是一个描述了HTTP状态代码的元组。HTTP状态代码是当你请求网页的时候web服务器返回的一个特殊值。当你请求不存在的网页时,就会返回404 Not Found。

let http404Error = (404, "Not Found")  // http404Erroris of type (Int, String)

(404, "Not Found")元组把一个Int和一个String组合起来表示HTTP状态代码的两种不同的值:数字和人类可读的描述。它可以被描述为“一个类型为(Int, String)”的元组

  再比如let student = ("001", "Wenxin", "11",

"女", "六一班")可以代表某个学生的元组(学号, 姓名, 年龄, 性别, 班级)。

  你也可以将一个元组的内容分解成单独的常量或变量,这样你就可以正常的使用它们了:

let http404Error = (404, "NotFound")

let (statusCode, statusMessage) = http404Error

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

// prints "The status code is404"

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

// prints "The status message is NotFound"

  当你分解元组的时候,如果只需要使用其中的一部分数据,不需要的数据可以用下划线(_)代替:

let http404Error = (404, "NotFound")

let (justTheStatusCode, _) = http404Error

print("The status code is \(justTheStatusCode)")

// prints "The status code is404"

另一种方法就是利用从零开始的索引数字访问元组中的单独元素:

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

// prints "The status code is404"

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

// prints "The status message is NotFound"

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

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

在命名之后,你就可以通过访问名字来获取元素的值了:

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

// prints "The status code is200"

print("The status message is \(http200Status.description)")

// prints "The status message isOK"

作为函数返回值时,元组非常有用。

例如:定义了一个叫做minMax(array:)的函数,它可以找到类型为Int的数组中最大数字和最小数字。

func minMax(array: [Int]) -> (min: Int, max:Int) {

var currentMin = array[0]

var currentMax = array[0]

for value in array[1..

ifvalue < currentMin {

currentMin= value

}else if value > currentMax {

currentMax= value

}

}

return (currentMin,currentMax)

}

函数minMax(array:)返回了一个包含两个Int值的元组。这两个值被 min和max 标记,这样当查询函数返回值的时候就可以通过名字访问了。

小问题:理论上用字典或者是建一个Model也能实现函数返回多值的问题,那元组与这两种方式相比有什么优势?欢迎评论区留言!!!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 元组 定义: 可以将多个不同类型的值合成单个复合值。(可以是任意类型的) 使用:可以将内容分为常量或变量进行常规访...
    永断阎罗阅读 355评论 0 1
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,448评论 0 10
  • 凡是都女人天生带一种自怜自艾的悲情。无论多么简单直白的故事,经她轻轻一点化,立刻就会变成情深义重的牺牲和付出。然后...
    嘴嘴剑客阅读 445评论 0 0
  • 一人有难,八方支援,众志成城,共渡难关, 一人有难众人帮,众人拾材火焰高, 从上午九点到晚上六点,七个小时,筹款1...
    梧桐夜雨821012阅读 289评论 0 0