Simpler array bounds checking.
This commit is contained in:
parent
75847de50b
commit
e22f528cf3
@ -2,3 +2,4 @@
|
||||
|
||||
- [david-swift](https://github.com/david-swift)
|
||||
- [Greg Cotten](https://github.com/gregcotten)
|
||||
- [Zev Eisenberg](https://github.com/ZevEisenberg)
|
||||
|
||||
@ -91,23 +91,16 @@ extension Array {
|
||||
/// ```
|
||||
public subscript(safe index: Int?) -> Element? {
|
||||
get {
|
||||
if let index, checkIndex(index) {
|
||||
if let index, indices.contains(index) {
|
||||
return self[index]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
set {
|
||||
if let index, let value = newValue, checkIndex(index) {
|
||||
if let index, let value = newValue, indices.contains(index) {
|
||||
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
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user