Created
February 26, 2020 23:59
-
-
Save dnedrow/c44acf08db02595c4fd601ee9e94eb45 to your computer and use it in GitHub Desktop.
This extension to Array provides safe access to any index in an array, with a clean non-crashy result.
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
| // | |
| // Array_SafeAccess.swift | |
| // | |
| // Created by Zhao, Tyler on 6/26/19. | |
| // | |
| import Foundation | |
| /// This protocol describes a function designed to return an optional | |
| /// on a bad array access. | |
| public protocol SafeIndexAccessible { | |
| // swiftlint:disable missing_docs | |
| associatedtype Element | |
| // swiftlint:enable missing_docs | |
| /// Safe access to objects in an array. On a bad access, nil is returned. | |
| /// Usage: | |
| /// ``` | |
| /// let myArr = [Double](repeating: 2.0, count 3) // Creates an array of size 3. | |
| /// let test = myArr[safe: 3] // test is nil, as there is no array element at index 3. | |
| /// ``` | |
| subscript(safe index: Int) -> Element? { get } | |
| } | |
| extension Array: SafeIndexAccessible { | |
| public subscript(safe index: Int) -> Element? { | |
| guard indices.contains(index) else { return nil } | |
| return self[index] | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment