Swift中的元组tuple的用法

用途

tuple用于传递复合类型的数据,介于基础类型和类之间,复杂的数据通过类(或结构)存储,稍简单的通过元组。

元组是使用非常便利的利器,有必要整理一篇博文。

定义

使用括号(), 括号内以逗号分割各种类型的数据, 形式如

(Int, String)
 或 (String, Int, String......)

如:

userZhangsan = ("Zhangsan", "张三", "越秀区清水濠小学", 9, "三年级", true)

//
读取元组中的元素,如: userZhangsan[0] //"Zhangsan" userZhangsan[1] //"张三" userZhangsan[2] //"越秀区清水濠小学" userZhangsan[3] //9 userZhangsan[4] //"三年级"

 

变量命名定义

还有另外一种方法也能以变量名的方式去访问元组中的数据,那就是在元组初始化的时候就给它一个变量名:

let userInfo = (name:"Zhangsan" ,isMale:true, age:22)
userInfo.name       //Zhangsan
userInfo.isMale     //true
userInfo.age        //22

分解和变量转换

对于

let http404Error = (404, "Not Found")

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

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

 

忽略部分值

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

let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// 输出 "The status code is 404"

 

多值赋值

//一般我们的变量赋值这么干:
var a = 1
var b = 2
var c = 3
//现在可以用一行替代: var (a, b, c) = (1, 2, 3) //变量交换就是这么简单: (a, b) = (b, a)

 

可变元组和不可变元组

用var定义的元组就是可变元组,let定义的就是不可变元组。不管是可变还是不可变元组,元组在创建后就不能对其长度进行增加和删除之类的修改,只有可变元组能在创建之后修改元组中的数据:

var userInfo = (name:"Bannings" ,true, age:22)    //定义可变元组
userInfo.name = "newName"
userInfo.name //newName

let userInfo1 = (name:"Bannings" ,true, age:22)    //定义不可变元组
userInfo1.name = "newName" //报错,不可修改

 

作为函数返回值

func divmod(_ a: Int, _ b:Int) -> (Int, Int) {
return (a / b, a % b)
}

divmod(7, 3) // (2, 1)
divmod(5, 2) // (2, 1)
divmod(12, 4) // (3, 0)

//或者使用命名的版本:

func divmod(_ a: Int, _ b:Int) -> (quotient: Int, remainder: Int) {
return (a / b, a % b)
}

divmod(7, 3) // (quotient: 2, remainder:1)
divmod(5, 2) // (quotient: 2, remainder:1)
divmod(12, 4) // (quotient: 3, remainder:0)

猜你喜欢

转载自www.cnblogs.com/starcrm/p/9961698.html