Last active
July 21, 2021 13:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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