02-Swift 逻辑分支

2016-11-15  本文已影响22人  magic_pill

一、if...else...语句

    //MARK: if...else 分支
    func testIF(cet4:Int,Scard:Bool)
    {
        if cet4 >= 425 {
            if Scard {
                print("进入考场参加六级考试")
            }else{
                print("滚回去拿学生证")
            }
        }else{
            print("没过四级,滚远一点")
        }
    }

    testIF(cet4: 425, Scard: false)

二、guard 语句

    //MARK : guard 分支
    func testGuard(cet4:Int,Scard:Bool)
    {
        //如果条件满足就执行后面的语句
        //如果条件不满足,就执行 else 里面的语句
        guard cet4 >= 425 else {
            print("四级没过,不允许参加六级考试")
            return
        }
        
        guard Scard else {
            print("回去拿学生证")
            return
        }
        
        print("进入考场参加六级考试")
    }

    testGuard(cet4: 425, Scard: true)

三、switch 语句

    //OC 中在 case 中定义变量要加 { }
    int a = 13;

    switch (a) {
        default:
            NSLog(@"默认");
            break;
        case 2:
            NSLog(@"sdfa");
            break;
        case 10:
        {   //在 case 中定义变量要加 { }
            int c = 20;
            NSLog(@"%d",c);
        }
            break;
    }
//MARK : switch 语句
let a = 10.1
func testSwitch(x:Double)
{
    switch x {
        case 10.1:
            print("参数为\\(x)")
            fallthrough
        case 5,10.1:
            print("参数为5或者10.1")
        default:
            print("不知道")
        }
}
testSwitch(x: a)

四、switch 语句的特殊使用方法

    //MARK - switch 语句的特殊使用方法
    func testSwitch01(score:Int)
    {
        switch score {
        case 0..<425:
            print("六级没过")
        case 425..<700:
            print("分数很高")
        case 700:
            let fallScore = 725
            print("快接近满分啦,满分为\\(fallScore)")
        default:
            print("不知道")
        }
    }

    testSwitch01(score: 700)
//元祖(以点坐标为例)
func testSwitch02(point:(x:Double,y:Double))
{
      switch point {
        case (0,0):
            print("点在原点")
        case (1...10.6,1...10):
            print("点在第一象限")
        case (_,0):
            print("点在 X 轴上")
        case (0,let y):     //值绑定
            print("在y轴上 \\(y) 位置")
        case let(x,y) where x>y:    //根据条件绑定
            print("在 y=x 直线下方,具体点位置为(\\(x),\\(y))")
        case let(x,y) where x<y:
            print("点在 y=x 上方,具体点位置为(\\(x),\\(y))")
        default:
            print("不知道")
      }
}
testSwitch02(point: (-40.1,-5))
上一篇 下一篇

猜你喜欢

热点阅读