Swift快速入门(三)

75 阅读1分钟

Swift 条件语句

  1. if语句:由一个布尔表达式和一个或多个执行语句组成。后可以有可选的 else 语句,  else if 语句
var a:Int = 2;

/* 条件判断 */
if a < 2 {
    print("a 小于 2");
}else if(a >2){
   print("a 大于 2");
}else{
  print("a 等于 2");
}
  1. switch 语句允许测试一个变量等于多个值时的情况.

注意: 在大多数语言中,switch 语句块中,case 要紧跟 break,否则 case 之后的语句会顺序运行,而在 Swift 语言中,默认是不会执行下去的,switch 也会终止。如果你想在 Swift 中让 case 之后的语句会按顺序继续运行,则需要使用 fallthrough 语句。

fallthrough

let a = 100
switch a {
 case 100:
print("------1-----")
//如果没有加fallthrough就默认break,fallthrough具有穿透效果
fallthrough

 case 200 :
 print ("------2-----")
 
 default:
 print("Not found")

}

可以匹配多个

let b = "d"

switch b {
case "a","b","c":
print("----abc---")
case"d","e","f":
print("----def---")
default:
print("Not found")
}

区间匹配

let c = 3 

 switch c {

  case 0 ..< 5 :

  print ("0<c<5")

  case 5..< 10:

  print("5<c<10")

  default:
  
  print("Not found")

}

*where关键字

// let d = (10,20)

let d = ( 30, 20)

 switch d {

 case let (n1,n2) where n1 > n2:

  print("n1 =\(n1)")

  print("n2 =\(n2)")

 case let (10 ,n3):

  print("n3 = \(n3) ")


  default :

  print("Not found")

}