Swift 5.7
@Hristo, Not only can we use a negative indexing in Swift subscript's functionality but also implement error handling to control whether you're "out of range" or not. So, use the following code for that.
let array: [Int] = [199, 288, 377, 455, 533, 622, 711]
enum SubscriptError: Error {
case greaterThanZero
case lessThanLastIndex
}
extension Collection {
public subscript(negative i: Int) -> () throws -> Element {
let backward = i - 1
if i > 0 {
return { throw SubscriptError.greaterThanZero }
}
if i < -1 * ((endIndex as! Int) - 1) {
print(endIndex)
return { throw SubscriptError.lessThanLastIndex }
}
return { self[index(endIndex, offsetBy: backward)] }
}
}
do {
try array[negative: -6]() // 199
} catch {
print("It's \(error)")
}
The results are as follows:
let array: [Int] = [199, 288, 377, 455, 533, 622, 711]
try array[negative: 2]() // "It's greaterThanZero"
try array[negative: 1]() // "It's greaterThanZero"
try array[negative: 0]() // 711
try array[negative: -1]() // 622
try array[negative: -2]() // 533
try array[negative: -3]() // 455
try array[negative: -4]() // 377
try array[negative: -5]() // 288
try array[negative: -6]() // 199
try array[negative: -7]() // "It's lessThanLastIndex"
try array[negative: -8]() // "It's lessThanLastIndex"