Swift学习-----分支

Swift 提供了类似 C 语言的流程控制结构(if/switch/for/while/dowhile)

分支if

* 只能以Bool作为条件语句

* 条件语句不需要加()

* {}不能省略

* Swift 中 if 分支的模式可以使用 where 语句来判断额外的条件

* 其它和 OC if 一样
let number = 10
if number == 10 {
    print("等于10")
}

if number >= 10 && number <= 20 {
    print("等于10")
}
Bool类型

* C语言和OC并没有真正的Bool类型

* OC语言的Bool类型YES/NO是`typedef signed char BOOL;`非0即真‘

Swift引入了真正的Bool类型true/false

* Swift中没有C和OC中非零即真的概念

* Swfit中逻辑值只有两个true/false

* 如果你在需要使用Bool类型的地方使用了非布尔值,Swift 的类型安全机制会报错
三目运算符
* 三目运算符的特殊在于它是有三个操作数的运算符, 它简洁地表达根据问题成立与否作出二选一的操作
* 格式: 问题 ? 答案1 : 答案2

 提示:
* Swift中三目运算符用得很多

 注意:
* 过度使用三目运算符会使简洁的代码变的难懂。我们应避免在一个组合语句中使用多个三目运算符

let number1 = 10

let result = (number1 == 10) ? 10 : 0

分支Switch
* OC中case后面必须加上break否则会贯穿, Swift不用
* Swift中如果想贯穿必须使用fallthrough
* OC中可以不写default,Swift中只有满足所有条件才能忽略default
* OC中default位置可以随便放,Swift不可以
* OC中在case中定义变量需要加大括号, 否则作用域混乱, Swift不用加大括号
* Swift中的switch可以判断区间和元祖
* Swift中case 分支的模式可以使用where语句来判断额外的条件

注意:
Swift中每一个 case 分支都必须包含至少一条语句, 不像 C 语言里的switch语句,在 Swift 中,switch语句不会同时匹配多个条件
switch(rank){
case "A":
case "B":
NSLog(@"还不错")
break
case "C":
NSLog("")
break
}

let age = 18

switch age {

    case 0:

        print("刚出生")

    case 18:

        print("刚成年")

        fallthrough

    case 40:

        print("一枝花")

        var name = "ssc"

    default:

        print("other")

}


// 判断元祖

let point = (0, 50)

switch point {

    case (0, 0):

        print("原点")

    case (50, 50):

        print("中点")

    case (100, 100):

        print("右下角")

    default:

        print("other")

}

// 了解

switch point {

    case let (x, y) where x == 0 && y == 0:

        print(x)

        print(y)

    case let (x, y) where x == 50 && y == 50:

        print(x)

        print(y)

    case let (x, y):

        print(x)

        print(y)

    default:

        print("other")

}

 
// 判断区间
// 闭区间   0...10  取值范围 0~10 包含头包含尾
// 半闭区间 0..<10  取值范围  0~9 包含头不包含尾

//let range = 0..<18
//let range = 18..<30
let range = 18...20
switch range {
//    case 0..<18:
//        print("未成年")
//    case 18..<30:
//        print("成年人")
//    default:
//        print("老炮")
    case 0...17:
        print("未成年")
    case 18...30:
        print("成年人")
    default:
        print("老炮")
}

let rank = "A"
switch rank {
//    case "A":
//        fallthrough
//    case "B":
//        print("还可以")
    case "A", "B":
        print("还可以")
    case "C":
        print("")
    default:
        print("回家吧")
}
原文地址:https://www.cnblogs.com/sleblogs/p/5774641.html