Trim end of line in swift, get runtime error

I am making a calculator application in Swift, as soon as my answer is received, I want to display it in UILabel. The only problem is I want to limit the response to 8 characters. Here is my code:

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

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

 fatal error: can not increment endIndex 

Any help is appreciated.

+1
source share
1 answer

There are two different functions of advance() :

 /// 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 verify that the result is within the valid line boundaries:

 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: Starting with Swift 3, β€œmove collections by 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) 

Simpler solution

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

still working.

+4
source

Source: https://habr.com/ru/post/1243108/


All Articles