推荐答案
// www.javascriptcn.com code example
// if 语句
let number = 10
if number > 5 {
print("Number is greater than 5")
} else {
print("Number is 5 or less")
}
// switch 语句
let letter = "A"
switch letter {
case "A":
print("Letter is A")
case "B":
print("Letter is B")
default:
print("Letter is something else")
}
// for 循环
for i in 1...5 {
print("Iteration \(i)")
}
// while 循环
var counter = 0
while counter < 5 {
print("Counter is \(counter)")
counter += 1
}
// repeat-while 循环
var repeatCounter = 0
repeat {
print("Repeat counter is \(repeatCounter)")
repeatCounter += 1
} while repeatCounter < 5本题详细解读
if 语句
if 语句用于根据条件执行代码块。如果条件为 true,则执行 if 块中的代码;否则,执行 else 块中的代码(如果有的话)。
switch 语句
switch 语句用于根据变量的值执行不同的代码块。每个 case 表示一个可能的值,default 用于处理所有未匹配的情况。Swift 的 switch 语句不需要显式的 break 语句,因为每个 case 执行完毕后会自动退出 switch 语句。
for 循环
for 循环用于遍历一个序列(如数组、范围等)。for-in 循环是最常见的形式,它会依次将序列中的每个元素赋值给循环变量,并执行循环体中的代码。
while 循环
while 循环在条件为 true 时重复执行代码块。每次循环开始前都会检查条件,如果条件为 true,则继续执行循环体;否则,退出循环。
repeat-while 循环
repeat-while 循环与 while 循环类似,但它会先执行一次循环体,然后再检查条件。如果条件为 true,则继续执行循环体;否则,退出循环。这种循环适用于至少需要执行一次循环体的情况。