Swift 語言陣列迭代程式


陣列用於按順序儲存相同資料型別元素。本文將學習如何編寫 Swift 程式來迭代陣列。

我們將使用以下方法遍歷陣列的每個元素:

  • 使用 for-in 迴圈

  • 使用 forEach() 函式

  • 使用 while 迴圈

  • 使用 enumerated() 函式

方法 1:使用 for-in 迴圈

可以使用 for-in 迴圈迭代陣列。

語法

for value in Sequence {
   // statement
}

其中,value 引數在迭代期間包含陣列中的一個元素,Sequence 表示陣列。

示例

以下 Swift 程式用於迭代陣列。

import Foundation
import Glibc

// Creating an array of string type
let names = ["Lovely", "Mukta", "Mohini", "Norma", "Eli"]

// Using for loop to iterate through each element of the array
print("Array elements are:")
for str in names {
   print(str)
}

輸出

Array elements are:
Lovely
Mukta
Mohini
Norma
Eli

在以上程式碼中,我們有一個字串型別的陣列。然後使用 for-in 迴圈迭代給定陣列的每個元素並列印這些元素。

方法 2:使用 forEach(_:) 函式

我們還可以使用 forEach(_:) 函式遍歷給定陣列的每個元素。forEach(_:) 函式對給定陣列的每個元素呼叫給定的閉包。它的工作原理與 for-in 迴圈相同。

語法

func forEach(_C: (Self.Element)throws->Void)rethrows

其中,C 表示一個閉包,它以給定陣列的元素作為引數。

示例

以下 Swift 程式用於迭代陣列。

import Foundation
import Glibc

// Creating an array of integer type
let MyValues = [20, 3, 3, 4, 21, 4, 7, 10, 8, 4, 2]

// Iterate over the elements of the array
// Using forEach() function
print("Array:")
MyValues.forEach { (ele) in
   print(ele)
}

輸出

Array:
20
3
3
4
21
4
7
10
8
4
2

在以上程式碼中,我們有一個整數型別的陣列。然後我們使用 forEach{(ele) in print(ele)} 函式以及閉包來迭代給定陣列的元素並在螢幕上列印它們。

方法 3:使用 while 迴圈

我們還可以使用 while 迴圈遍歷給定陣列的每個元素。

語法

while(condition){
   // Statement
}

其中,condition 是任何表示式,statement 是單個或多個語句塊。此處,while 迴圈僅在 condition 為 true 時迭代。如果 condition 為 false,則控制權將傳遞到 while 迴圈之後的語句。

示例

以下 Swift 程式用於迭代陣列。

import Foundation
import Glibc

// Creating an array of integer type
let MyValues = [2.0, 3.3, 3.1, 2.4, 0.21, 0.42, 1.7, 1.203, 8.9]

print("Array:")

// Iterate over the elements of the array
// Using while loop
var x = 0
while x < MyValues.count {
   print(MyValues[x])
   x += 1
}

輸出

Array:
2.0
3.3
3.1
2.4
0.21
0.42
1.7
1.203
8.9

在以上程式碼中,我們有一個雙精度型別的陣列。然後執行一個 while 迴圈來迭代 MyValues 陣列的每個元素並顯示 m。此處,x 表示元素的索引,因此在每次迭代中,x 的值增加 1 以移動到下一個元素。此迴圈持續到陣列結束。

方法 4:使用 enumerated() 函式

我們還可以使用 enumerated() 函式迭代給定陣列的每個元素。此函式返回一個 (a, b) 對的序列,其中“a”表示從零開始的連續整數,“b”表示給定陣列中的一個元素。

語法

func enumerated()

此處,該函式不接受任何引數。

示例

以下 Swift 程式用於迭代陣列。

import Foundation
import Glibc

// Creating an array of integer type
let MyString = ["oo", "pp", "ee", "ww", "ss", "qq", "ll", "rr", "tt"]

print("Array elements along with their index:")

// Iterate over the elements of the array
// Using enumerated() function 
for (indexVal, ele) in MyString.enumerated() 
{
   print("Element [\(indexVal)]: \(ele)")
}

輸出

Array elements along with their index:
Element [0]: oo
Element [1]: pp
Element [2]: ee
Element [3]: ww
Element [4]: ss
Element [5]: qq
Element [6]: ll
Element [7]: rr
Element [8]: tt

在以上程式碼中,我們有一個字串型別的陣列。然後我們執行一個 for 迴圈以及 enumerated() 函式。此處,enumerated() 函式返回兩個值,即索引值和給定陣列中的元素。

結論

這就是我們如何迭代陣列的方法。所有討論的方法都執行良好,您可以根據需要使用任何一種方法。

更新於: 2023 年 2 月 8 日

3K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告