如果我在Swift中有一个数组,并尝试访问一个越界的索引,有一个不足为奇的运行时错误:

var str = ["Apple", "Banana", "Coconut"]

str[0] // "Apple"
str[3] // EXC_BAD_INSTRUCTION

然而,我本以为有了Swift带来的所有可选的链接和安全性,做这样的事情是微不足道的:

let theIndex = 3
if let nonexistent = str[theIndex] { // Bounds check + Lookup
    print(nonexistent)
    ...do other things with nonexistent...
}

而不是:

let theIndex = 3
if (theIndex < str.count) {         // Bounds check
    let nonexistent = str[theIndex] // Lookup
    print(nonexistent)   
    ...do other things with nonexistent... 
}

但事实并非如此——我必须使用ol' if语句来检查并确保索引小于str.count。

我尝试添加我自己的下标()实现,但我不确定如何将调用传递给原始实现,或者访问项目(基于索引)而不使用下标符号:

extension Array {
    subscript(var index: Int) -> AnyObject? {
        if index >= self.count {
            NSLog("Womp!")
            return nil
        }
        return ... // What?
    }
}

当前回答

如果您确实需要这种行为,那么您需要的是Dictionary而不是Array。字典在访问缺少的键时返回nil,这是有意义的,因为要知道一个键是否存在于字典中要困难得多,因为这些键可以是任何东西,而在数组中,键必须在一个范围内:0才能计数。在这个范围内迭代是非常常见的,在这个范围内,您可以绝对确定在循环的每次迭代中都有一个真实的值。

我认为它不能这样工作的原因是Swift开发人员的设计选择。举个例子:

var fruits: [String] = ["Apple", "Banana", "Coconut"]
var str: String = "I ate a \( fruits[0] )"

如果您已经知道索引的存在,就像您在使用数组的大多数情况下所做的那样,那么这段代码非常棒。然而,如果访问下标可能返回nil,那么您已经将Array的下标方法的返回类型更改为可选。这将更改您的代码为:

var fruits: [String] = ["Apple", "Banana", "Coconut"]
var str: String = "I ate a \( fruits[0]! )"
//                                     ^ Added

这意味着每次遍历数组或使用已知索引执行其他操作时,都需要展开一个可选对象,因为很少会访问出界索引。Swift的设计者选择了更少的可选项的展开,以访问越界索引时的运行时异常为代价。崩溃比由数据中某个地方的nil导致的逻辑错误更可取。

我同意他们的观点。因此,您不会更改默认的Array实现,因为您将破坏所有期望从数组中获得非可选值的代码。

相反,您可以继承Array的子类,并重写下标以返回可选对象。或者,更实际地说,您可以使用非下标方法来扩展Array。

extension Array {

    // Safely lookup an index that might be out of bounds,
    // returning nil if it does not exist
    func get(index: Int) -> T? {
        if 0 <= index && index < count {
            return self[index]
        } else {
            return nil
        }
    }
}

var fruits: [String] = ["Apple", "Banana", "Coconut"]
if let fruit = fruits.get(1) {
    print("I ate a \( fruit )")
    // I ate a Banana
}

if let fruit = fruits.get(3) {
    print("I ate a \( fruit )")
    // never runs, get returned nil
}

Swift 3更新

func get(index: Int) ->T?需要func get(index: Int) ->元素?

其他回答

如果您确实需要这种行为,那么您需要的是Dictionary而不是Array。字典在访问缺少的键时返回nil,这是有意义的,因为要知道一个键是否存在于字典中要困难得多,因为这些键可以是任何东西,而在数组中,键必须在一个范围内:0才能计数。在这个范围内迭代是非常常见的,在这个范围内,您可以绝对确定在循环的每次迭代中都有一个真实的值。

我认为它不能这样工作的原因是Swift开发人员的设计选择。举个例子:

var fruits: [String] = ["Apple", "Banana", "Coconut"]
var str: String = "I ate a \( fruits[0] )"

如果您已经知道索引的存在,就像您在使用数组的大多数情况下所做的那样,那么这段代码非常棒。然而,如果访问下标可能返回nil,那么您已经将Array的下标方法的返回类型更改为可选。这将更改您的代码为:

var fruits: [String] = ["Apple", "Banana", "Coconut"]
var str: String = "I ate a \( fruits[0]! )"
//                                     ^ Added

这意味着每次遍历数组或使用已知索引执行其他操作时,都需要展开一个可选对象,因为很少会访问出界索引。Swift的设计者选择了更少的可选项的展开,以访问越界索引时的运行时异常为代价。崩溃比由数据中某个地方的nil导致的逻辑错误更可取。

我同意他们的观点。因此,您不会更改默认的Array实现,因为您将破坏所有期望从数组中获得非可选值的代码。

相反,您可以继承Array的子类,并重写下标以返回可选对象。或者,更实际地说,您可以使用非下标方法来扩展Array。

extension Array {

    // Safely lookup an index that might be out of bounds,
    // returning nil if it does not exist
    func get(index: Int) -> T? {
        if 0 <= index && index < count {
            return self[index]
        } else {
            return nil
        }
    }
}

var fruits: [String] = ["Apple", "Banana", "Coconut"]
if let fruit = fruits.get(1) {
    print("I ate a \( fruit )")
    // I ate a Banana
}

if let fruit = fruits.get(3) {
    print("I ate a \( fruit )")
    // never runs, get returned nil
}

Swift 3更新

func get(index: Int) ->T?需要func get(index: Int) ->元素?

extension Array {
  subscript (safe index: UInt) -> Element? {
    return Int(index) < count ? self[Int(index)] : nil
  }
}

使用上述提到的扩展返回nil,如果任何时候索引超出界限。

let fruits = ["apple","banana"]
print("result-\(fruits[safe : 2])")

结果-无

我对数组做了一个简单的扩展

extension Array where Iterator.Element : AnyObject {
    func iof (_ i : Int ) -> Iterator.Element? {
        if self.count > i {
            return self[i] as Iterator.Element
        }
        else {
            return nil
        }
    }

}

它的设计完美无缺

例子

   if let firstElemntToLoad = roots.iof(0)?.children?.iof(0)?.cNode, 

Alex的回答对这个问题有很好的建议和解决方案,然而,我碰巧发现了一个更好的实现这个功能的方法:

extension Collection {
    /// Returns the element at the specified index if it is within bounds, otherwise nil.
    subscript (safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

例子

let array = [1, 2, 3]

for index in -20...20 {
    if let item = array[safe: index] {
        print(item)
    }
}

我发现安全数组获取,设置,插入,删除非常有用。我更倾向于记录并忽略错误,因为所有其他错误很快就会变得难以管理。完整代码如下

/**
 Safe array get, set, insert and delete.
 All action that would cause an error are ignored.
 */
extension Array {

    /**
     Removes element at index.
     Action that would cause an error are ignored.
     */
    mutating func remove(safeAt index: Index) {
        guard index >= 0 && index < count else {
            print("Index out of bounds while deleting item at index \(index) in \(self). This action is ignored.")
            return
        }

        remove(at: index)
    }

    /**
     Inserts element at index.
     Action that would cause an error are ignored.
     */
    mutating func insert(_ element: Element, safeAt index: Index) {
        guard index >= 0 && index <= count else {
            print("Index out of bounds while inserting item at index \(index) in \(self). This action is ignored")
            return
        }

        insert(element, at: index)
    }

    /**
     Safe get set subscript.
     Action that would cause an error are ignored.
     */
    subscript (safe index: Index) -> Element? {
        get {
            return indices.contains(index) ? self[index] : nil
        }
        set {
            remove(safeAt: index)

            if let element = newValue {
                insert(element, safeAt: index)
            }
        }
    }
}

测试

import XCTest

class SafeArrayTest: XCTestCase {
    func testRemove_Successful() {
        var array = [1, 2, 3]

        array.remove(safeAt: 1)

        XCTAssert(array == [1, 3])
    }

    func testRemove_Failure() {
        var array = [1, 2, 3]

        array.remove(safeAt: 3)

        XCTAssert(array == [1, 2, 3])
    }

    func testInsert_Successful() {
        var array = [1, 2, 3]

        array.insert(4, safeAt: 1)

        XCTAssert(array == [1, 4, 2, 3])
    }

    func testInsert_Successful_AtEnd() {
        var array = [1, 2, 3]

        array.insert(4, safeAt: 3)

        XCTAssert(array == [1, 2, 3, 4])
    }

    func testInsert_Failure() {
        var array = [1, 2, 3]

        array.insert(4, safeAt: 5)

        XCTAssert(array == [1, 2, 3])
    }

    func testGet_Successful() {
        var array = [1, 2, 3]

        let element = array[safe: 1]

        XCTAssert(element == 2)
    }

    func testGet_Failure() {
        var array = [1, 2, 3]

        let element = array[safe: 4]

        XCTAssert(element == nil)
    }

    func testSet_Successful() {
        var array = [1, 2, 3]

        array[safe: 1] = 4

        XCTAssert(array == [1, 4, 3])
    }

    func testSet_Successful_AtEnd() {
        var array = [1, 2, 3]

        array[safe: 3] = 4

        XCTAssert(array == [1, 2, 3, 4])
    }

    func testSet_Failure() {
        var array = [1, 2, 3]

        array[safe: 4] = 4

        XCTAssert(array == [1, 2, 3])
    }
}