Swift - for-in 迴圈



Swift for-in 迴圈

for-in 迴圈迭代遍歷集合元素,例如範圍、陣列、集合、字典等。它迭代遍歷指定集合的每個元素,無需顯式索引操作。它是最常用的控制流語句,因為它以非常簡潔易讀的方式表達邏輯。

它也相容函數語言程式設計,這意味著您可以輕鬆地將高階函式(如 filter()、map()、reduce() 等)與 for-in 迴圈一起使用。

語法

以下是 for-in 迴圈的語法:

for index in var{
   Statement(s)
}

流程圖

下面的流程圖將展示 for-in 迴圈的工作原理:

For-In Loop

示例

Swift 程式演示 for-in 迴圈的使用。

import Foundation

var someInts:[Int] = [10, 20, 30]

for index in someInts {
   print( "Value of index is \(index)")
}

輸出

它將產生以下輸出:

Value of index is 10
Value of index is 20
Value of index is 30

使用下劃線 "_" 的 Swift for-in 迴圈

在 for-in 迴圈中,我們還可以使用下劃線 "_" 來忽略給定集合中的值。在這裡,我們在 for-in 迴圈中用下劃線 "_" 代替 **變數名**。它將在迭代時忽略當前值。當我們只想迭代給定次數並且不需要集合中的值時,通常會使用它。

語法

以下是使用下劃線的 for-in 迴圈的語法:

for _ in var{
   Statement(s)
}

示例

Swift 程式演示如何使用帶下劃線的 for-in 迴圈。

import Foundation

let numbers = [3, 5, 76, 12, 4]

// Using the underscore to ignore the values
for _ in numbers {

   // Following code will execute in each iteration
   print("Hello!! for-in loop!")
}

輸出

它將產生以下輸出:

Hello!! for-in loop!
Hello!! for-in loop!
Hello!! for-in loop!
Hello!! for-in loop!
Hello!! for-in loop!

Swift for-in 迴圈與範圍

我們也可以將範圍與 for-in 迴圈一起使用。範圍是在 for-in 迴圈中表示值範圍的最簡單方法,它可以是開區間、閉區間或半開區間。for-in 迴圈迭代遍歷給定範圍中的每個值,並且在每次迭代中,迴圈變數都取範圍中當前元素的值。

語法

以下是使用範圍的 for-in 迴圈的語法:

// With a closed range
for variableName in start…end{
   Statement(s)
}

// With half-open range
for variableName in start..<end{
   Statement(s)
}

示例

Swift 程式演示如何使用帶範圍的 for-in 迴圈。

import Foundation

// Using closed Range
print("Loop 1:")
for x in 1...6 {
   print(x)
}

// Using half-open Range
print("Loop 2:")
for y in 1..<6 {
   print(y)
}

輸出

它將產生以下輸出:

Loop 1:
1
2
3
4
5
6
Loop 2:
1
2
3
4
5

Swift for-in 迴圈與 stride() 函式

我們可以將 stride() 函式與 for-in 迴圈一起使用。stride() 函式以特定步長迭代遍歷一系列值。它通常用於實現更復雜的迭代模式,或建立具有自定義迭代模式的迴圈。

語法

以下是使用 **stride()** 函式的 for-in 迴圈的語法:

for variableName in stride(from: value, to: value, by: value){
   statement(s)
}

引數

**stride()** 函式接受三個引數:

  • **from** - 包含範圍的起始值。

  • **to** - 包含範圍的結束值。不包含該值。

  • **by** - 包含值之間的步數或步長。如果其值為正,則步長向上迭代;如果其值為負,則步長向下迭代。

示例

Swift 程式演示如何使用帶 **stride()** 函式的 for-in 迴圈。

import Foundation

// The stride() function moves in upward direction
print("Loop 1:")
for x in stride(from: 1, to: 7, by: 2) {
   print(x)
}

// The stride() function moves in downward direction
print("\nLoop 2:")
for y in stride(from: 7, to: 1, by: -2) {
   print(y)
}

輸出

它將產生以下輸出:

Loop 1:
1
3
5

Loop 2:
7
5
3

Swift for-in 迴圈與 where 子句

Swift 還提供了一個 where 子句,我們可以將其與 for-in 迴圈一起使用。where 子句用於從給定集合中過濾出僅滿足 where 子句中指定條件的元素。它可以與所有可迭代集合(如陣列、集合和字典)一起使用。

語法

以下是帶 where 子句的 for-in 迴圈的語法:

for variableName in collectionName where condition{
   Statement(s)
}

示例

Swift 程式演示如何使用帶 where 子句的 for-in 迴圈。

import Foundation
let nums = [43, 23, 66, 12, 2, 45, 33]

// Using the where clause to filter out only even elements from the array
for n in nums where n % 2 == 0 {
   print("Even number is \(n)")
}

輸出

它將產生以下輸出:

Even number is 66
Even number is 12
Even number is 2
廣告