Swift is said to be designed with safety in mind. If that’s so, then why doesn’t it have a built-in solution for the “index out of range” error?
It could, for example, return optional values when array subscripts are used:
let friends = ["Jack", "Lisa", "Brian"]
let friend1 = friends[1] // Optional("Lisa")
let friend3 = friends[3] // nil
Dictionaries do use that pattern, and there’s no problem with that.
I know I can compare array indices with friends.count
, but doing so constantly is tiresome.
I just don’t understand why this thing isn’t solved by Swift designers already. Maybe there are some widespread conventions or technical restrictions I’m not aware of. In that case, I’d be grateful for an explanation.