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)