【问题标题】:Swift 4 - 'substring(to:)' is deprecated - Alternative To My Code [duplicate]Swift 4 - 'substring(to:)' 已弃用 - 我的代码的替代方案 [重复]
【发布时间】:2019-06-11 11:21:10
【问题描述】:

我的代码如下

   var theReview = addReview.text
    let len2 = addReview.text.utf16.count

    if len2 > 3000 {

        theReview = theReview?.substring(to: (theReview?.index((theReview?.startIndex)!, offsetBy: 3000))!)

    }

如果文本长度超过 3000 个字符,我的目标是获取文本的前 3000 个字符。

但是,我收到以下警告:

'substring(to:)' 已弃用:请使用字符串切片下标 使用 'partial range upto' 运算符

什么可以替代我的代码。我不是一个非常专业的编码器。所以任何帮助都会很棒。

【问题讨论】:

    标签: ios swift swift4


    【解决方案1】:

    只需使用所需的lengththeReview 上调用prefix(_:)

    函数前缀(_ maxLength: Int) -> 子字符串

    返回一个子序列,最长为指定的最大长度,包含 集合的初始元素。

    如果最大长度超过了 集合,结果包含集合中的所有元素

    var theReview = addReview.text
    theReview = String(theReview.prefix(3000))
    

    注意:无需检查theReview's length是否超过3000。它将由prefix(_:) 自己处理。

    【讨论】:

    • 我猜这甚至可以压缩成let theReview = String(addReview.text.prefix(3000))
    【解决方案2】:

    这对你有帮助吗

    var theReview = addReview.text
    theReview = String(theReview.prefix(3000))
    

    【讨论】:

    • 查看 PGDev 的答案以更好地使用prefix()
    • @JoakimDanielson 是的,我看到 PGDev 的答案,更好的一个
    • 即使字符串长度低于 3000 .prefix 仍然有效。
    • @user28434 是的,这就是我们将它嵌入到 if 条件中的原因
    • @NaqeebAhmed,我的意思是 if 不需要,在最坏的情况下你会得到原始字符串。
    【解决方案3】:

    将 String init 与 slice 一起使用。

    let index = theReview.index(theReview.startIndex, offsetBy: 3000)
    theReview = String(theReview[theReview.startIndex..<index])
    

    prefix 如之前的答案所述

    【讨论】:

    • @JoakimDanielson 确定。但长度检查存在问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 2020-05-24
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    相关资源
    最近更新 更多