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);

}

 

posted @ 2017-08-02 11:21  Today2013  阅读(154)  评论(0编辑  收藏  举报