定义一个Tuple
let color = (1.0,1.0,1.0,1.0)
switch color{
case (0.0,0.5...1.0,let blue,_): //匹配第一个值为0.0第二个值为0.5到1.0第三四值为任意,并将第三个值传给blue变量
println("Blue is \(blue)")
case let (r,g,b,1.0) where r == g && g == b: //额外条件where 本个亦是的值要相等
println("Opaque grey \(r * 100)%")
default:
println("unkonw")
}
匹配模式混合应用,更加强大及有效,
class State{
var name:String?
var population:Double?
var abbr:String?
init(name:String,pop:Double,abbr:String){
self.name = name
self.population = pop
self.abbr = abbr
}
}
func stateFormPlist(list:Dictionary<String,AnyObject>) -> State? {
switch(list["name"],list["pupulation"],list["abbr"]){ //创建Tuple,检查要检查的元素
case (
.Some(let listName as NSString), //对应相对应位置的Tuple元素
.Some(let pop as Double),
.Some(let abbr as NSString)
) where abbr.length == 1:
return State(name: listName, pop: pop, abbr: abbr)
default:
println("b")
}
return nil
}
var mylist = ["name":"Beijing","population":20000000,"abbr":"京"]
var result = stateFormPlist(mylist)
println(result?.abbr) //京
println(result?.name) //Beijing
println(result?.population) //20000000
元祖就说完了,接下来定义一个Struct
struct Color {
var red:Double?
var green:Double?
var blue:Double?
var alpha:Double?
init(red:Double,green:Double,blue:Double,alpha:Double){
self.red = red
self.green = green
self.blue = blue
self.alpha = alpha
}
}
var mycolor = Color(red: 10, green: 20, blue: 60, alpha: 1.0)
switch mycolor{
case let a where a.red == 10 && a.blue == 60:
println("yes")
default:
println("unkonw")
}
使用下划线(_)忽略部分数值:
var loginResult = (true, "Login Success")
let (isLoginSuccess,_) = loginResult
if isLoginSuccess {
println("登录成功")
println(loginResult.0) //访问Tuple中的第一项
println(loginResult.1) //访问Tuple中的第二项
}