Skip to content

Instantly share code, notes, and snippets.

@atierian
Last active July 21, 2021 13:29
Show Gist options
  • Save atierian/523b4e6b9b56ad717449faa052560638 to your computer and use it in GitHub Desktop.
Save atierian/523b4e6b9b56ad717449faa052560638 to your computer and use it in GitHub Desktop.
Extension on subscript of Array to return nil if subscript is out of range
import UIKit
import XCTest
extension Collection {
subscript(guarded idx: Index) -> Element? {
indices.contains(idx) ? self[idx] : nil
}
}
class GuardedSubscriptTests: XCTestCase {
let array = (0...99).map { $0 }
func testExisting() {
let index = 25
XCTAssertEqual(index, array[guarded: index])
}
func testRandomExisting() {
let randomExistingIndex = Int.random(in: 0...99)
XCTAssertEqual(randomExistingIndex, array[guarded: randomExistingIndex])
}
func testRandom() {
let randomIndex = Int.random(in: 0...Int.max)
let shouldElement = randomIndex <= 99 ? randomIndex : nil
XCTAssertEqual(shouldElement, array[guarded: randomIndex])
}
func testOutOfBounds() {
let outOfBoundsIndex = 100
XCTAssertNil(array[guarded: outOfBoundsIndex])
}
}
GuardedSubscriptTests.defaultTestSuite.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment