Merge pull request #7 from ZevEisenberg/patch-1

Simpler array bounds checking
This commit is contained in:
david-swift 2024-03-26 17:29:29 +01:00 committed by GitHub
commit b17ec73bae
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 3 additions and 9 deletions

View File

@ -2,3 +2,4 @@
- [david-swift](https://github.com/david-swift) - [david-swift](https://github.com/david-swift)
- [Greg Cotten](https://github.com/gregcotten) - [Greg Cotten](https://github.com/gregcotten)
- [Zev Eisenberg](https://github.com/ZevEisenberg)

View File

@ -91,23 +91,16 @@ extension Array {
/// ``` /// ```
public subscript(safe index: Int?) -> Element? { public subscript(safe index: Int?) -> Element? {
get { get {
if let index, checkIndex(index) { if let index, indices.contains(index) {
return self[index] return self[index]
} }
return nil return nil
} }
set { set {
if let index, let value = newValue, checkIndex(index) { if let index, let value = newValue, indices.contains(index) {
self[index] = value self[index] = value
} }
} }
} }
/// Check if a given index is valid for the array.
/// - Parameter index: The index to test.
/// - Returns: Return whether the index is valid or not.
private func checkIndex(_ index: Int) -> Bool {
index < count && index >= 0
}
} }