您的位置:首页 > 移动开发 > Swift

【swift-总结】控制流

2015-06-27 08:57 429 查看

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语句都与其他语言类似
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: