Inconsistent behavior of .index(before:) between Array and String

let array = [Int]()
_ = array.index(before: array.endIndex)     // <=== is -1

let s = ""
_ = s.index(before: endIndex)       // crash

I tried all combinations of index(before:) and index(after:): Array return invalid values, while String crash. What the reason for this inconsistency? Is it because they want Array to be fast and do no error check at all and simply do the math and return whatever?

Shouldn't they both crash? Maybe crash in debug mode and disable error check and return invalid result in non-debug mode?

Given that you're going into undefined territory by violating .index(before:)'s requirement, it could crash the program (as String did), it could return an invalid value (as Array did), etc. At least it doesn't set printer on fire, yet.

It's been my belief that Swift wants to do away with undefined behaviours, but we can't have them all, I guess. Best to just try to avoid these encounters as much as possible.

Terms of Service

Privacy Policy

Cookie Policy