控制流

for in
  1. for in 跨度遍历
var a = [1,2,3,4,5,6,7,8,9]

for item in stride(from: 0, to: 8, by: 2){
    print(a[item])
}

for item in stride(from: 0, through: 8, by: 2) {
    print(a[item])
}

While循环
  1. while语句是先判断后循环,和其他语言while语句一样。
  2. repeat while语句是先循环后判断,和其他语言do while语句一样
Switch
  1. switch语句被增强了,还可以匹配字串,字符,整数,元组,数组等等类型了
  2. case 后边可以写多个值,并且还可以使用区间
  3. case:下边必须做处理(这是单一匹配)
  4. 不用写break语句,它是不存在贯穿想象的。
  5. 如果匹配到多个case那么会执行第一个匹配到的case,忽略其他case
//多值匹配
var b: Character = "a"
switch b {
case "a","A":
    print("a || A")
default:
    print("others")
}

//区间匹配
var c = 23
switch c {
case 0..<10:
    print("< 10")
case 10..<20:
    print("< 20")
case 20..<30:
    print("< 30")
default:
    print("others")
}

//匹配元组
var a = (0,0)
switch a {
case (_,0):
    print("x轴")
case (0,_):
    print("y轴")
case (0,0):
    print("原点")
default:
    print("others")
}

//数组匹配
var temp = [1,2]
switch temp {
case [1,0]:
    print("1,0")
case [2,1]:
    print("0,1")
case [1,2]:
    print("1,2")
default:
    print("others")
}
  1. 值绑定
var a = (2,3)
switch a {
case (let x,0):
    print("x 轴:\(x)")
case (0,let y):
    print("y 轴:\(y)")
case (let x, let y):
    print("x:\(x) y:\(y)")
}
  1. where条件
var a = (3,-3)

switch a {
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:\(x) y:\(y)")
}
  1. 复合匹配
    允许用逗号隔开不同的匹配类型,但是只能有相同的类型
    符合匹配值绑定中,每个逗号分隔的选项中都要有要绑定的值变量,并且所处位置类型要一致
//复合匹配
let a = "a"
switch a {
case "a", "b", "c", "d",
     "e":
    print("a - e")
case "A", "B", "C","D",
     "E":
    print("A - E")
default:
    print("others")
}

//复合匹配值绑定
let bc = (3, 4)
switch bc {
case (let x, 3), (3, let x):
    print("match")
default:
    print("others")
}
控制转移语句
  1. continue
    用在for in中用来结束本次遍历,进入下一次遍历。
  2. break
    用在for in中时候是为了结束整个循环。
    用在switch中时候是为了忽略某一个分支
  3. 贯穿
    fallthrough可以贯穿case
var a = "a"
switch a {
case "a":
    print("a")
    fallthrough
default:
    print("default")
}

  1. 标签
var a = "a"

whileLoop: while a == "a" {
    let b = "a"
    switch b {
    case "a":
        print("a")
        break whileLoop
    default:
        print("others")
    }
}
  1. guard语句
    如果条件满足有值,就往下执行,如果没值就执行else里代码,并且else里边必须要有结束控制语句
var a = "a"

func test(vale: String?) {
    guard let _ = vale else {
        print("temp = nil")
        return
    }
    print("vale有值")
}

test(vale: nil)
  1. 检测API可用性
if #available(iOS 11, *) {
    print("iOS11以上")
}else{
    print("iOS11以下")
}
总结

结束控制语句

  1. for in中想要结束当前循环进入下次循环,我们用continue
  2. for in中想结束整个循环用break
  3. while中结束循环用break
  4. switch中忽略分支用break
  5. 函数中结束向下继续执行用return
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值