Swift 数组检查索引是否存在

swiftserver side programmingprogramming更新于 2025/9/22 16:52:17

在 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
   print("Index \(targetIndex) exists in the array \(inputArr
if targetIndex < inputArray.count {ay)")
} 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 方法检索索引处的元素(如果存在)。方法的选择取决于上下文和您的个人偏好。



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部