Swift程式:查詢陣列中指定項的首次出現索引
陣列用於按順序儲存相同資料型別的元素。
在這裡,我們將學習如何編寫一個Swift程式來查詢陣列中指定項的首次出現索引。
為此,我們將使用以下方法來查詢陣列元素首次出現的索引:
使用使用者自定義函式
使用firstIndex()函式
方法1:使用使用者自定義函式
為了查詢陣列中指定元素首次出現的索引,我們建立一個函式,該函式迭代遍歷每個元素及其索引,並檢查當前值是否等於指定元素。如果是,則返回該當前索引。如果迴圈結束且未找到元素,則返回nil。
演算法
步驟1 - 建立一個函式。
步驟2 - 執行for迴圈。
步驟3 - 檢查當前元素是否等於指定元素。如果是,則返回當前索引。
步驟4 - 如果迴圈結束且未找到指定元素,則返回nil。
步驟5 - 建立一個數組並將它與元素一起傳遞給函式。
步驟6 - 列印結果
示例
下面的Swift程式用於查詢陣列中指定項的首次出現索引。
import Foundation
import Glibc
// Function to find the index of the first occurrence of the specified item in the array
func findFirstIndex(ele: Int, in arr: [Int]) -> Int? {
for (index, value) in arr.enumerated() {
if value == ele {
return index
}
}
return nil
}
// Creating an array of integer type
let numbers = [12, 9, 3, 6, 88, 23, 4, 6, 4, 23, 6]
if let index = findFirstIndex(ele: 6, in: numbers) {
print("The first occurrence of 6 is at index \(index)")
} else {
print("Element 6 is not found in the give array")
}
輸出
The first occurrence of 6 is at index 3
在上面的程式碼中,我們有一個整數型別的陣列。現在,我們建立一個名為findFirstIndex()的函式,並將元素和陣列傳遞給它。在這個函式中,我們執行一個for迴圈,它迭代遍歷原始陣列的每個元素,並使用enumerated()函式獲取索引和元素。在for迴圈內,我們檢查當前元素是否等於指定元素。如果當前元素等於指定元素,則此函式返回當前索引。如果迴圈結束並且沒有元素等於指定元素,則此函式返回nil。
方法2:使用firstIndex(of:)函式
Swift提供了一個名為firstIndex(of:)的內建函式。此函式返回指定元素在給定陣列中首次出現的索引。如果在給定陣列中找不到指定元素,則它將返回nil。
語法
Func firstIndex(of: Element)
這裡,Element表示要在陣列中搜索的項。
演算法
步驟1 - 建立一個整數型別的陣列。
步驟2 - 使用if-else語句檢查使用firstIndex(of:)函式在陣列中找到指定元素的首次出現索引。
步驟3 - 如果在給定陣列中找到該元素,則顯示索引值。
步驟4 - 如果未找到該元素,則列印“未找到元素”。
示例
下面的Swift程式用於查詢陣列中指定項的首次出現索引。
import Foundation
import Glibc
// Creating an array of integer type
let mArray = [20, 3, 3, 4, 21, 4, 7, 10, 8, 4, 2]
// Finding the index of the first occurrence of the specified item in the array
if let index = mArray.firstIndex(of: 4) {
print("The first occurrence of 4 is at index \(index)")
}
else {
print("Element 4 is not found in the given array")
}
輸出
The first occurrence of 4 is at index 3
在上面的程式碼中,我們有一個整數陣列。然後,我們使用firstIndex(of:)函式查詢元素4在陣列中首次出現的索引。如果在陣列中找到該數字,則顯示該元素及其索引值。否則,顯示“元素未找到”。這裡我們使用if let與firstIndex(of:)函式一起使用,因為此函式返回可選Int值,因此需要使用if let解包。
結論
在本文中,我們使用了兩種不同的方法來查詢陣列中指定項的首次出現索引。在第一種方法中,我們使用了使用者自定義函式,而在第二個示例中,我們使用了內部函式firstIndex(of:)來查詢索引。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP