Trying to get to grips with Swift programming, I wrote the following:
var s : String = "dog" var i1 : String.Index = advance(s.startIndex, 2) var t1 : String = s.substringToIndex(i1) Executing this code in a playground, t1 has the value "do", as expected. However, if I try to construct an index that exceeds the string's length, this happens:
var s : String = "dog" var i2 : String.Index = advance(s.startIndex, 4) var t2 : String = s.substringToIndex(i2) This time, the line var i2 ... shows the error
Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP,subcode=0x0).
I read the Swift documentation, but the entry for String.substringToIndex reads in its entirety:
func substringToIndex(index: String.Index) -> String[Foundation]Returns a new string containing the characters of the String up to, but not including, the one at a given index.
The result is not optional, nor does the function possess an error parameter or return an empty string in case of faulty arguments.
I don't know how to prevent this by not creating an index in the first place, because String does not have a length or count property. Since Swift does not have exception handling, how can programs recover from errors like this?
This is on OS X 10.10.2, Xcode 6.2.