Swift中的if
、else if
和else
用於條件判斷。
let number = 10
if number > 0 {
print("The number is positive")
} else if number < 0 {
print("The number is negative")
} else {
print("The number is zero")
}
三元運算子是一種簡化的條件語句,形式為condition ? trueValue : falseValue
。
let number = 10
let result = number > 0 ? "positive" : "non-positive"
print(result) // positive
switch
語句用於多條件分支判斷。
let fruit = "apple"
switch fruit {
case "apple":
print("It's an apple")
case "banana":
print("It's a banana")
default:
print("Unknown fruit")
}
let number = 7
switch number {
case 0:
print("Zero")
case 1..<5:
print("Between 1 and 4")
case 5...10:
print("Between 5 and 10")
default:
print("Greater than 10")
}
for
迴圈用於遍歷集合或範圍。
for i in 1...5 {
print(i)
}
let numbers = [1, 2, 3, 4, 5]
for number in numbers {
print(number)
}
while
迴圈在條件為真時反覆執行。
var count = 1
while count <= 5 {
print(count)
count += 1
}
repeat-while
迴圈至少執行一次,然後在條件為真時繼續執行。
var count = 1
repeat {
print(count)
count += 1
} while count <= 5
循環可以在其他循環內部嵌套。
for i in 1...3 {
for j in 1...3 {
print("i = \\\\(i), j = \\\\(j)")
}
}
break
語句立即終止當前的循環或switch語句。
for i in 1...5 {
if i == 3 {
break
}
print(i)
}
// Output: 1, 2
continue
語句立即結束本次循環,並開始下一次循環。
for i in 1...5 {
if i == 3 {
continue
}
print(i)
}
// Output: 1, 2, 4, 5
label
用於標識特定的循環,可以與break
或continue
結合使用來控制多重循環。
outerLoop: for i in 1...3 {
for j in 1...3 {
if j == 2 {
break outerLoop
}
print("i = \\\\(i), j = \\\\(j)")
}
}
// Output: i = 1, j = 1
fallthrough
用於switch
語句中,讓程序繼續執行後續的case區塊,而不進行條件檢查。這在Swift中不常見,但在需要有意識地繼續執行下一個case時很有用。
let number = 3
switch number {
case 3:
print("Three")
fallthrough
case 4:
print("Four")
default:
print("Default case")
}
// Output:
// Three
// Four
// Default case
return
語句用於從函數或方法中返回,並可以返回一個值。
func greet(name: String) -> String {
return "Hello, \\\\(name)!"
}
let greeting = greet(name: "Alice")
print(greeting) // Hello, Alice!
guard
語句用於提前退出,當條件不成立時,立即退出當前代碼塊。它常與else
一起使用,用於函數或循環內部。
func printPositiveNumber(_ number: Int) {
guard number > 0 else {
print("The number is not positive")
return
}
print("The number is \\\\(number)")
}
printPositiveNumber(5) // The number is 5
printPositiveNumber(-3) // The number is not positive
defer
語句用於延遲執行某個代碼塊,直到當前的範圍退出時。這對於需要在函數結束時執行清理操作非常有用。
func example() {
defer {
print("This will be executed last")
}
print("This will be executed first")
}
example()
// Output:
// This will be executed first
// This will be executed last