swift3.0之Switch语句

普通Switch

let someCharacter: Character = "z"

switch someCharacter {

case "a":
    print("The first letter of the alphabet")

case "z":
    print("The last letter of the alphabet")

default:
    print("Some other character")

}

 

Switch(元组)

我们可以使用元组在同一个switch语句中测试多个值。元组中的元素可以是值,也可以是区间。另外,使用下划线(_)来匹配所有可能的值。

let somePoint = (1, 1)

switch somePoint {

case (0, 0):
    print("(0, 0) is at the origin")

case (_, 0):
    print("(\(somePoint.0), 0) is on the x-axis")

case (0, _):
    print("(0, \(somePoint.1)) is on the y-axis")

case (-2...2, -2...2):
    print("(\(somePoint.0), \(somePoint.1)) is inside the box")

default:
    print("(\(somePoint.0), \(somePoint.1)) is outside of the box")

}
// 输出 "(1, 1) is inside the box"

 

Switch-值绑定(Value Bindings

case 分支允许将匹配的值绑定到一个临时的常量或变量,并且在case分支体内使用 —— 这种行为被称为值绑定(value binding),因为匹配的值在case分支体内,与临时的常量或变量绑定。

let anotherPoint = (2, 0)

switch anotherPoint {

case (let x, 0):
    print("on the x-axis with an x value of \(x)")

case (0, let y):
    print("on the y-axis with a y value of \(y)")

case let (x, y):
    print("somewhere else at (\(x), \(y))")

}
// 输出 "on the x-axis with an x value of 2"

 

Switch-Where

let yetAnotherPoint = (1, -1)

switch yetAnotherPoint {

case let (x, y) where x == y:
    print("(\(x), \(y)) is on the line x == y")

case let (x, y) where x == -y:
    print("(\(x), \(y)) is on the line x == -y")

case let (x, y):
    print("(\(x), \(y)) is just some arbitrary point")

}
// 输出 "(1, -1) is on the line x == -y"

 

Switch-复合匹配

当多个条件可以使用同一种方法来处理时,可以将这几种可能放在同一个case后面,并且用逗号隔开。

let someCharacter: Character = "e"

switch someCharacter {

case "a", "e", "i", "o", "u":
    print("\(someCharacter) is a vowel")

case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
     "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
    print("\(someCharacter) is a consonant")

default:
    print("\(someCharacter) is not a vowel or a consonant")

}
// 输出 "e is a vowel"

转自:http://www.swift51.com/swift3.0/chapter2/05_Control_Flow.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值