For-In 循环
for-in循环是用来遍历一个集合里面的所有元素,例如由数字表示的区间、数组中的元素、字符串中的字符。
for index in 1...5
{
print("\(index)*5 = \(index*5)")
}
//1*5 = 5
//2*5 = 10
//3*5 = 15
//4*5 = 20
//5*5 = 25
for in遍历数组
var arrayStr:[String] = ["h","b","c","d","g","f"]
for indexStr in arrayStr
{
print("遍历数组\(indexStr)")
}
//遍历数组h
//遍历数组b
//遍历数组c
//遍历数组d
//遍历数组g
//遍历数组f
遍历字典
var dict = ["1" :"d","2":"b","3":"g"]
for (key1,value1) in dict
{
print("key = \(key1) value = \(value1)")
}
//key = 2 value = b
//key = 1 value = d
//key = 3 value = g
While
while循环从计算单一条件开始。如果条件为true,会重复运行一系列语句,直到条件变为false。
下面是一般情况下 while 循环格式:
while condition {
statements
}
Repeat-While
while循环的另外一种形式是repeat-while,它和while的区别是在判断循环条件之前,先执行一次循环的代码块,然后重复循环直到条件为false。
Swift语言的repeat-while循环合其他语言中的do-while循环是类似的。
一般情况下 repeat-while循环的格式:
repeat {
statements
} while condition
If
if语句最简单的形式就是只包含一个条件,当且仅当该条件为true时,才执行相关代码:
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
}
// 输出 "It's very cold. Consider wearing a scarf."
if语句允许二选一,当条件为false时,执行 else 语句:
temperatureInFahrenheit = 40
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
} else {
print("It's not that cold. Wear a t-shirt.")
}
// 输出 "It's not that cold. Wear a t-shirt."