Swift陣列:檢查索引是否存在
在Swift中,有多種方法可以檢查陣列中是否存在某個索引。可以使用startIndex、endIndex、indices屬性和count屬性。本文將介紹一些檢查索引的示例。
示例1:使用FirstIndex & EndIndex
可以透過將索引與陣列的startIndex和endIndex屬性進行比較來檢查特定索引是否在Swift陣列中存在。以下是一個示例。
import Foundation let inputArray = [1, 2, 3, 4, 5] let targetIndex = 3 if targetIndex >= inputArray.startIndex && targetIndex < inputArray.endIndex { print("Index \(targetIndex) exists in the array \(inputArray)") } else { print("Index does not exist in the array") }
輸出
Index 3 exists in the array [1, 2, 3, 4, 5]
在這個例子中,我們首先確定要驗證的索引和名為inputArray的陣列。接下來,我們使用if語句將targetIndex與inputArray的startIndex和endIndex屬性進行比較。如果targetIndex大於等於startIndex,小於endIndex且小於targetIndex,則表示targetIndex存在於陣列中;在這種情況下,會列印一條相應的提示資訊。如果沒有,則列印一條訊息,指出該索引不存在於陣列中。
示例2:使用Indices屬性
import Foundation let inputArray = [1, 2, 3, 4, 5] let targetIndex = 3 if inputArray.indices.contains(targetIndex) { print("Index \(targetIndex) exists in the array \(inputArray)") } else { print("Index does not exist in the array") }
輸出
Index 3 exists in the array [1, 2, 3, 4, 5]
在這個例子中,我們使用陣列的indices屬性來檢查targetIndex是否存在。indices屬性返回陣列所有有效索引的範圍。我們可以使用contains()方法來檢查targetIndex是否在這個範圍內。
示例3:使用可選繫結
import Foundation let inputArray = [1, 2, 3, 4, 5] let targetIndex = 3 if let _ = inputArray.indices.firstIndex(of: targetIndex) { print("Index \(targetIndex) exists in the array \(inputArray)") } else { print("Index does not exist in the array") }
輸出
Index 3 exists in the array [1, 2, 3, 4, 5]
在這個例子中,我們使用陣列的indices屬性的firstIndex()方法來獲取與targetIndex匹配的元素的索引。如果存在這樣的索引,該方法將返回它,我們可以使用可選繫結來列印一條訊息,說明該索引存在。如果該方法返回nil,則該索引不存在於陣列中。
示例4:使用Count屬性
import Foundation let inputArray = [1, 2, 3, 4, 5] let targetIndex = 3 if targetIndex < inputArray.count { print("Index \(targetIndex) exists in the array \(inputArray)") } else { print("Index does not exist in the array") }
輸出
Index 3 exists in the array [1, 2, 3, 4, 5]
在這個例子中,我們檢查targetIndex是否小於陣列的count屬性。如果是,則該索引存在於陣列中,我們列印一條訊息來說明這一點。如果不是,則該索引不存在於陣列中。請注意,我們不需要檢查targetIndex是否大於等於0,因為count屬性總是非負的。
示例5:使用Guard語句
import Foundation func checkIndex() { let inputArray = [1, 2, 3, 4, 5] let targetIndex = 3 guard targetIndex < inputArray.count else { print("Index does not exist in the array") return } print("Index \(targetIndex) exists in the array \(inputArray)") } checkIndex()
輸出
Index 3 exists in the array [1, 2, 3, 4, 5]
在這個例子中,我們使用guard語句來檢查targetIndex是否小於陣列的count屬性。如果是,我們列印一條訊息,說明該索引存在。如果不是,我們列印一條訊息,說明該索引不存在,並從當前作用域返回。
結論
在Swift中,有多種方法可以檢查陣列中是否存在某個索引。可以使用startIndex和endIndex屬性將索引與有效索引範圍進行比較,使用indices屬性的contains()方法檢查索引是否在此範圍內,或使用count屬性檢查索引是否小於陣列的長度。
還可以使用guard語句或三元運算子來列印一條訊息,說明索引是否存在,或者使用get方法在索引存在的情況下檢索該索引處的元素。方法的選擇取決於上下文和個人偏好。