我正在Swift中创建一个计算器应用程序,一旦获得我的答案,我想在UILabel中显示它。唯一的问题是我想将所述答案限制为8个字符。这是我的代码:
let answerString = "\(answer)"
println(answer)
calculatorDisplay.text = answerString.substringToIndex(advance(answerString.startIndex, 8))
这不会返回任何编译器错误,但在运行时我得到:
fatal error: can not increment endIndex
非常感谢任何和所有帮助。
答案 0 :(得分:4)
有两种不同的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
使用第二个,您可以确保结果在字符串的有效范围内:
let truncatedText = answerString.substringToIndex(advance(answerString.startIndex, 8, answerString.endIndex))
更新 Swift 2 / Xcode 7:
let truncatedText = answerString.substringToIndex(answerString.startIndex.advancedBy(8, limit: answerString.endIndex))
但更简单的解决方案是
let truncatedText = String(answerString.characters.prefix(8))
更新 Swift 3 / Xcode 8 beta 6:截至Swift 3,“收藏品移动 他们的索引“,相应的代码现在是
let to = answerString.index(answerString.startIndex,
offsetBy: 8,
limitedBy: answerString.endIndex)
let truncatedText = answerString.substring(to: to ?? answerString.endIndex)
更简单的解决方案
let truncatedText = String(answerString.characters.prefix(8))
仍然有效。