//使用范围
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默认没有穿透功能,不需要加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语句都与其他语言类似
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/ttf1993/article/details/46658893