Jeśli mam tablicę w Swift i próbuję uzyskać dostęp do indeksu, który jest poza zakresem, pojawia się nieoczekiwany błąd w czasie wykonywania:
var str = ["Apple", "Banana", "Coconut"]
str[0] // "Apple"
str[3] // EXC_BAD_INSTRUCTION
Jednak pomyślałbym z całym opcjonalnym łańcuchem i bezpieczeństwem, jakie zapewnia Swift, byłoby trywialne zrobić coś takiego:
let theIndex = 3
if let nonexistent = str[theIndex] { // Bounds check + Lookup
print(nonexistent)
...do other things with nonexistent...
}
Zamiast:
let theIndex = 3
if (theIndex < str.count) { // Bounds check
let nonexistent = str[theIndex] // Lookup
print(nonexistent)
...do other things with nonexistent...
}
Ale tak nie jest - muszę użyć instrukcji ol ' if, aby sprawdzić i upewnić się, że indeks jest mniejszy niż str.count.
Próbowałem dodać własną subscript()implementację, ale nie jestem pewien, jak przekazać wywołanie do oryginalnej implementacji lub uzyskać dostęp do elementów (na podstawie indeksu) bez użycia notacji w indeksie dolnym:
extension Array {
subscript(var index: Int) -> AnyObject? {
if index >= self.count {
NSLog("Womp!")
return nil
}
return ... // What?
}
}