【swift-总结】控制流

for语句

//使用范围
for index in 1...5 {
    print(index);
}
//如果不需要使用循环变量,可以使用下划线替代
var time = 5;
var i = 0
for _ in 1...time {
    print("第\(++i)次");
}
//遍历数组
let numbers = ["one", "two", "three"];
for number in numbers {
    print(number);
}
//遍历字典
let numStr = ["one": 1, "two": 2, "three": 3];
for (str, num) in numStr {
    print("\(str) is \(num)");
}
//遍历字符串的字符
for character in "hello".characters {
    print(character);
}
//经典for循环
for var i=0; i<5; i++ {
    print(i);
}
//新型for循环
for i in 0..<3 {
    forstLoop += i;
}
相等于
for var i=0; i<3; i++ {
    forstLoop += i;
}

switch语句

switch默认没有穿透功能,不需要加break。如果要有穿透要使用fallthrough

let num = "one"
switch num {
case "one":
    print("one");
case "two":
    print("two")
default:
    print("错误");
}
switch num {
case "one", "two":
    print("你好");
default:
    print("不好");
}
//使用范围
let score = 88;
switch score {
case 0...60:
    print("不及格");
case 60...70:
    print("中等");
case 70...80:
    print("良好");
case 80...100:
    print("优秀");
default:
    print("超鬼");
}
//使用点
let point = (1, 1)

switch point {
case (0, 0):
    print("原点");
case (_, 0):
    print("x轴上的点");
case (0, _):
    print("Y轴上的点");
default:
    print("普通点");
}

赋值

let anotherPoint = (2, 0);
switch anotherPoint {
case (let x, 0):
    print("在X轴上面的点是\(x)");
case (0, let y):
    print("在Y轴上面的点是\(y)");
case let(x, y):
    print("其他点(\(x), \(y))");
}

还可以加where条件,有赋值的时候不能使用default

let wherePoint = (-1, -1);

switch wherePoint {
case let(x, y) where x == y:
    print("x=y的点是(\(x), \(y))" );

case let(x, y) where x == -y:
    print("x=-y的点是(\(x), \(y))");
case let (x, y):
    print("其他的两个点")
}

另外还有continue,break,return,do-while,while,if语句都与其他语言类似

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值