检查数组中对象是否越界的最佳方法

3

如何最好地检查数组中特定索引处的对象是否存在(在范围内)?

如果可以这么简单就好了,但不幸的是这是不可能的:

let testArray = ["A", "B", "C", "D"]

if let result = testArray[6] {
    println("Result: \(result)")
}
else {
    println("Result does not exist. Out of bounds.")
}

我需要检查总数吗?

谢谢!


4
好的,请检查数量。 - Wain
6个回答

20

你也可以扩展Array,这样你就能使用if-let进行检查:

extension Array {
    func at(index: Int) -> Element? {
        if index < 0 || index > self.count - 1 {
            return nil
        }
        return self[index]
    }
}

let arr = [1, 2, 3]

if let value = arr.at(index: 2) {
    print(value)
}

使用未声明的类型 T? - Ankit Kumar Gupta
1
@AnkitKumarGupta 感谢您指出这个已经过时了,代码已更新。 :) - Aleksi Sjöberg
谢谢!干杯~~ - Ankit Kumar Gupta
简单解决方案真棒。 - Rajesh Loganathan

6
您可以使用~=运算符与indices函数结合使用,这是创建容器完整索引范围的快捷方式:
let a = [1,2,3]
let idx = 3  // one past the end

if indices(a) ~= idx {
    println("within")
}
else {
    println("without")
}

需要注意的是,此方法适用于任何具有可比较索引的容器,而不仅仅是像数组一样具有整数索引的容器。习惯将索引视为数字通常是一个好习惯,因为它可以帮助您更加普遍地考虑对不具备这些索引的容器(如字符串或字典)上的算法:

let s = "abc"
let idx = s.endIndex

idx < count(s)  // this won't compile

idx < s.startIndex  // but this will

// and so will this
if indices(s) ~= idx {
    println("within")
}
else {
    println("without")
}

如果您的算法越通用,那么它们就越容易被拆分成通用代码并增加重用性。


那是一个“丑陋”的运算符;看起来像是将lhs赋值为lhs ~ rhs的结果 - 就像其他<op>=运算符一样。 - GoZoner
同意,我认为它受到了awk的启发。在我看来,使用“~==”会更好。 - Airspeed Velocity
甚至更好的是,Range 应该有一个包含运算符,但不幸的是,它无法利用比较器,因为范围的索引是无限制的。 - Airspeed Velocity
1
“indices(a)”已被弃用。请使用“a.indices”替代。 - 无论如何,我真的很喜欢这个解决方案。 - Robert

3

在Swift中有一种新的(好用的)方法:

array.indices.contains(index)


小心- contains(_:) 的时间复杂度为O(n),其中n是序列的长度。 - alegelos

2

@alkku已经有了,但为了简单起见并使用所有语言中最不常用的句法形式?::

extension Array {
    func atIndex(index: Int) -> T? {
      return (0 <= index && index < self.count
              ? self[index]
              : nil)
    }
}

1

检查使用的对象索引是否大于等于零且小于数组的总数,就像这样:

//Here index is object you want for
if(index >= 0 && index < [yourArray count])
{
   //inside of array
}
else
{
   //out of bound
}

1
我认为 <= 需要改成 >= - keithbhunter
1
那是Objective-C。你可能想表达的是 if index < testArray.count { ... } :) - Martin R
即使在 Obj-C 中,减一后使用 <= 也毫无意义。 - Airspeed Velocity
第一句话仍然有错误,“应该小于或等于数组的总数”,它应该是“应该小于数组的总数”。 - Bhumit Mehta

-1

在Swift中检查索引是否在数组界限内,您可以使用以下方法:

if index < testArray.count {
    //index is inside bounds
} else {
    //index is outside bounds
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接