0

My code was as below

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

    if len2 > 3000 {

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

    }

My aim was to get the first 3000 characters of the text if it is longer than 3000 characters.

However, I get the warning below:

'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range upto' operator

What can be an alternative to my code. I am not a very professional coder. So any help would be great.

mag_zbc
  • 6,801
  • 14
  • 40
  • 62
saner
  • 821
  • 2
  • 10
  • 32

3 Answers3

5

Simply call prefix(_:) on theReview with the required length.

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))

Note: There is no need to check if the theReview's length exceeds 3000. It will be handled by prefix(_:) itself.

PGDev
  • 23,751
  • 6
  • 34
  • 88
1

might this could help you

var theReview = addReview.text
theReview = String(theReview.prefix(3000))
Naqeeb
  • 1,121
  • 8
  • 25
0

Use String init with slice.

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

or prefix as mentioned in previous answers

Kirow
  • 1,077
  • 12
  • 25