string - Error handling in Swift non-optional-valued functions -
this question has answer here:
trying grips swift programming, wrote following:
var s : string = "dog" var i1 : string.index = advance(s.startindex, 2) var t1 : string = s.substringtoindex(i1)
executing code in playground, t1
has value "do"
, expected. however, if try construct index exceeds string's length, happens:
var s : string = "dog" var i2 : string.index = advance(s.startindex, 4) var t2 : string = s.substringtoindex(i2)
this time, line var i2 ...
shows error
execution interrupted, reason: exc_bad_instruction (code=exc_i386_invop,subcode=0x0).
i read swift documentation, entry string.substringtoindex
reads in entirety:
func substringtoindex(index: string.index) -> string
[foundation]returns new string containing characters of string to, not including, 1 @ given index.
the result not optional, nor function possess error parameter or return empty string in case of faulty arguments.
i don't know how prevent not creating index in first place, because string
not have length
or count
property. since swift not have exception handling, how can programs recover errors this?
this on os x 10.10.2, xcode 6.2.
the error in advance(s.startindex, 4)
cannot advance eyond 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 recover , continue. enter lldb commands investigate (type :help assistance.)
you avoid providing 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 swift1.2, in xcode6-beta3.
Comments
Post a Comment