Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

ios - Trim end off of string in swift, getting error at runtime

I'm making a calculator app in Swift, once my answer is obtained I want to display it in a UILabel. Only problem is I want to limit said answer to 8 characters. Here is my code:

let answerString = "(answer)"
    println(answer)
    calculatorDisplay.text = answerString.substringToIndex(advance(answerString.startIndex, 8))

This does not return any compiler errors but at runtime I get:

fatal error: can not increment endIndex

Any and all help would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two different advance() functions:

/// Return the result of advancing `start` by `n` positions. ...
func advance<T : ForwardIndexType>(start: T, n: T.Distance) -> T

/// Return the result of advancing start by `n` positions, or until it
/// equals `end`. ...
func advance<T : ForwardIndexType>(start: T, n: T.Distance, end: T) -> T

Using the second one you can ensure that the result is within the valid bounds of the string:

let truncatedText = answerString.substringToIndex(advance(answerString.startIndex, 8, answerString.endIndex))

Update for Swift 2/Xcode 7:

let truncatedText = answerString.substringToIndex(answerString.startIndex.advancedBy(8, limit: answerString.endIndex))

But a simpler solution is

let truncatedText = String(answerString.characters.prefix(8))

Update for Swift 3/Xcode 8 beta 6: As of Swift 3, "collections move their index", the corresponding code is now

let to = answerString.index(answerString.startIndex,
                            offsetBy: 8,
                            limitedBy: answerString.endIndex)
let truncatedText = answerString.substring(to: to ?? answerString.endIndex)

The simpler solution

let truncatedText = String(answerString.characters.prefix(8))

still works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...