0

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.

0

1 Answer 1

1

The error is in advance(s.startIndex, 4) as you cannot advance eyond the end index:

 1> var s = "dog" s: String = "dog" 2> var i1 = advance(s.startIndex, 4) fatal error: can not increment endIndex i1: String.Index = { _base = { /* ... */ } /* ... */ } Execution interrupted. Enter Swift code to recover and continue. Enter LLDB commands to investigate (type :help for assistance.) 

You avoid this by providing an end index as:

 3> var i1 = advance(s.startIndex, 4, s.endIndex) i1: String.Index = { _base = { /* ... */ } /* ... */ } 

and then:

 4> s.substringToIndex(i1) $R0: String = "dog" 

at least for Swift1.2, in Xcode6-Beta3.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.