在swift中修剪字符串结束,在运行时获得错误 [英] Trim end off of string in swift, getting error at runtime

查看:102
本文介绍了在swift中修剪字符串结束,在运行时获得错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Swift中制作一个计算器应用程序,一旦得到我的答案,我想在UILabel中显示它。唯一的问题是我想将所述答案限制为8个字符。这是我的代码:

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.

推荐答案

有两种不同的 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 ensure that the result is within the valid bounds of the string:

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,集合移动
他们的索引,相应的代码现在

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)

更简单的解决方案

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

仍然有效。

这篇关于在swift中修剪字符串结束,在运行时获得错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆