//在 Swift中,默认可以不写break,并不会贯穿后面的条件。当匹配的case分支中的代码执行完毕后,程序会终止switch语句,而不会继续执行下一个case分支。case、default后面不能写大括号{}。
var typeValue = 1
switch typeValue {
case 1:
print("typeValue is 1")
case 2:
print("typeValue is 2")
default:
print("typeValue is other")
}//typeValue is 1
switch typeValue {
case 1:
print("typeValue is 1")
fallthrough
case 2:
print("typeValue is 2")
default:
print("typeValue is other")
}//typeValue is 1 typeValue is 2
switch typeValue {
case 1:
print("typeValue is 1")
fallthrough
case 2:
print("typeValue is 2")
default: //在此情景默认不能省略。
print("typeValue is other")
}
- case、default 后面至少有一条语句,如果不想做任何事加break即可。
switch typeValue {
case 1:
print("typeValue is 1")
case 2:
print("typeValue is 2")
default:
break
}
- 如果能保证已处理所有情况,也可以不必使用default。
enum Answer {
case right,wrong
}
let answer = Answer.right
switch answer {
case Answer.right:
print("right")
case Answer.wrong:
print("wrong")
}//right
- 已确定answer是Answer类型,可以省略Answer。
switch answer {
case .right:
print("right")
case .wrong:
print("wrong")
}//right
- switch也支持Character,String。
let stringType = "Jack"
switch stringType {
case "Jack":
fallthrough
case "Rose":
print("Rose is perspn")
default:
break
}//right Rose is perspn
let character:Character = "a"
switch character {
case "a","A":
print("The letter A")
default:
print("Not the letter A")
}//The letter A
switch stringType {
case "Jack","Rose":
print("Rose is perspn")
default:
break
}//right Rose is perspn
let countValue = 62
switch countValue {
case 0:
print("none")
case 1..<5:
print("few")
case 5..<12:
print("several")
case 12..<100:
print("dozens of")
default:
print("many")
}//dozens of
let pointValue = (1,1)
switch pointValue {
case (0,0):
print("the origin")
case (_,0):
print("on the x-axis")
case (0,_):
print("on the y-axis")
case (-2...2,-2...2):
print("inside the box")
default:
print("outside of the box")
}//inside the box
let sizeValue = (2,0)
switch sizeValue {
case (let x,0):
print("x is \(x)")
case (0,let y):
print("y is \(y)")
case (let x,let y):
print("x is \(x),y is \(y)")
}//x is 2 [必要时let也可以改为var]
let rectValue = (2,2)
switch rectValue {
case let (x,y) where x == y:
print("x == y")
case let (x,y) where x == -y:
print("x == -y")
case let (x,y):
print("x is \(x),y is \(y)")
}//x == y
var numbersArray = [10,20,-10,3,-30]
var sumValue = 0
for num in numbersArray where num > 0{
sumValue += num
}
outer:for i in 1...4 {
for j in 1...4 {
if j == 3 {
continue outer
}
if i == 3 {
break outer
}
print("i = \(i),j = \(j)")
}
}