12-Swift条件语句

Swift 提供两种类型的条件语句: if 语句和 switch 语句。通常,当条件较为简单且可能的情况很少时,使用 i f 语句。而 switch 语句更适用于条件较复杂、有更多排列组合的时候。并且 switch 在需要用到模式匹配(patte rn-matching)的情况下会更有用。

1. if 条件语句

1> 必须要有大括号
2> 没有"非零即真"的概念,只有ture/false

let num = 20
if num > 10{
    print("大于10");
}else{
    print("小于或等于10")
}

2.switch条件语句

1> 值可以是任何类型
"字符串" 
"a", "e", "i", "o", "u"
"b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"
1..<5
(0,0)  (_,0)  (0,_)  (-2...2,-2...2)
(let x, 0)  (0, let y)  let(x, y)
let (x, y) where x == y  let (x, y) where x == -y  let (x, y) 
(let distance, 0), (0, let distance)

2> 作用域仅在 case 内部

3> 不需要 break

4> 每一个 case 都要有代码

let name = "nick"

switch name {
case "nick":
    let age = 18
    print("one  \(age)")
case "fil":
    print("two")
case "Davi":
    print("three")
case "tom","ningcol":
    print("tomAndNingcol")
default:
    print("other")
}

你可能感兴趣的:(12-Swift条件语句)