专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > Swift

【swift-小结】控制流

发布时间:2011-06-30 07:25:21 文章来源:www.iduyao.cn 采编人员:星星草
【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语句都与其他语言类似

友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: