[Swift]元组-Tuples

1、元组(tuple)是由多个值组成的复合值类型

let id = (7010,23,"htx","05\\10\\93"); //分别代表学号,年龄,姓名,出生年月

2、当你函数需要返回多个值时,元组这个时候非常有用,你可以使用下标方式访问元组中得值,如0..1以此类推,如下:

var number = id.0
println(number)
var age = id.1
println(age)
var name = id.2
println(name)
var birthdate = id.3
println(birthdate)
/* 结果: 7010 23 htx 05\10\93 */

3、为元组中每个元素命名:

let myid = (number:7010,age:23,name:"HTX",birthdate:"05\\10\\93")

4、增加格式化:

func format(idinput:(Int,Int,String,String))->String{
    return "number is \(idinput.0) \n age is \(idinput.1) \n name is \(idinput.2) \n birthdate is \(idinput.3)"
}
println(format(myid))
/*
输出结果:
number is 7010 
 age is 23 
 name is HTX 
 birthdate is 05\10\93
*/

5、元组时可以分解的

let (numbers,ages,names,birthdates) = myid

println("number is \(numbers) \n age is \(ages) \n name is \(names) \n birthdate is \(birthdates)")
/*
输出结果:
number is 7010 
 age is 23 
 name is HTX 
 birthdate is 05\10\93
*/

6、元组也可部分分解,忽略其他值,忽略的值用”_”代替即可

let (rel, _,res, _) = myid

println("rel is \(rel) \n res is \(res)")
/*
输出结果:
rel is 7010 
 res is HTX
*/

你可能感兴趣的:(swift,Tuple)