Simpler array bounds checking.

This commit is contained in:
Zev Eisenberg 2024-03-26 09:26:00 -04:00 committed by Zev Eisenberg
parent 75847de50b
commit e22f528cf3
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
}
} }