Swift 4 - 'substring(to:)' 已弃用 - 替代我的代码

Swift 4 - 'substring(to:)' is deprecated - Alternative To My Code

我的代码如下

   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:)' is deprecated: Please use String slicing subscript with a 'partial range upto' operator

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

只需在 theReview 上用所需的 length 调用 prefix(_:)

func prefix(_ maxLength: Int) -> Substring

Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.

If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection

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

注:如果theReview's length超过3000则不需要检查。它将由 prefix(_:) 自己处理。

这可能对你有帮助

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

对切片使用字符串初始化。

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

prefix如之前的答案所述