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

隐身守侯 提交于 2019-11-28 13:08:19

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!