当前位置: 代码迷 >> 综合 >> 知识点13:switch语句
  详细解决方案

知识点13:switch语句

热度:82   发布时间:2023-09-29 18:46:32.0
  • 关于隐式贯穿。
//在 Swift中,默认可以不写break,并不会贯穿后面的条件。当匹配的case分支中的代码执行完毕后,程序会终止switch语句,而不会继续执行下一个case分支。case、default后面不能写大括号{}。var typeValue = 1switch typeValue {
case 1:print("typeValue is 1")
case 2:print("typeValue is 2")
default:print("typeValue is other")
}//typeValue is 1
  •  使用fallthrough可以实现贯穿效果。
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 必须要保证能处理所有情况。
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.rightswitch 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 perspnlet 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]
  •  where语句。
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 == yvar 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)")}
}

  相关解决方案