Swift学习之元组(Tuple)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift学习之元组(Tuple)相关的知识,希望对你有一定的参考价值。

定义

元组是由若干个类型的数据组成,组成元组的数据叫做元素,每个元素的类型都可以是任意的。

用法一

let tuples1 = ("Hello", "World", 2017)

//元组跟数组一样,其元素的角标是从0开始  可以用 tuple1.0  tuple1.1 tuple1.2进行取值

 print("get first value \(tuples1.0), get the second value \(tuples1.1), get the third value \(tuples1.2)")

用法二

let tuples2 = (first:"Hello", second:"World", third:2017)

//此中用法的元组的取值可以用 tuple2.first tuple2.second tuple3.third

 print("get the first value \(tuples2.first), get the second value \(tuples2.second), get the third value \(tuples2.third)")

用法三

//变量接收数值法

let (x, y, z) = ("Hello", "World", 2017);

        print("get x is \(x) get y is \(y) get z is \(z)")

 //用_取出某些元素的值忽略_对应的值

 let (a, _, b) = ("Hello", "World", 2017);

print("get x is \(a) get z is \(b)")

元组值得修改

let tuples2 = (first:"Hello", second:"World", third:2017)

//此中用法的元组的取值可以用 tuple2.first tuple2.second tuple3.third

 print("get the first value \(tuples2.first), get the second value \(tuples2.second), get the third value \(tuples2.third)")

 //此时会报错

 //tuples2.first = "test";  应将tuple2前的let 改成var可将元组变成可变元组

 

var tuples2 = (first:"Hello", second:"World", third:2017)

//此中用法的元组的取值可以用 tuple2.first tuple2.second tuple3.third

var print("get the first value \(tuples2.first), get the second value \(tuples2.second), get the third value \(tuples2.third)")

 tuples2.first = "test";  

print("get the first value \(tuples2.first), get the second value \(tuples2.second), get the third value \(tuples2.third)")

元组的高级应用

定义一个可以交换一个数组中两个元素的函数

func swap<T>(_ nums: inout [T], _ p: Int, _ q: Int) {

        (nums[p], nums[q]) = (nums[q], nums[p])

  }

var array = ["Hello", "World", 2017] as [Any]

for value in array {

print(value);

 }

swap(&array, 0, 2)

for value in array {

      print(value);

}

 

以上是关于Swift学习之元组(Tuple)的主要内容,如果未能解决你的问题,请参考以下文章

python学习之元组

python学习之数据类型—元组tuple

Python学习之元组

python学习之第十课时--基本数据类型(tuple)

python基础学习之02 元组

Swift 元组(Tuple)