Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

i've just converted my little app but i've found this error: 'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

my code is:

    let dateObj = dateFormatterFrom.date(from: dateStringa)       if dateObj != nil {         cell.detailTextLabel?.text = dateFormatterTo.string(from:(dateObj!))     } else {         let index = thisRecord.pubDate.index(thisRecord.pubDate.startIndex, offsetBy: 5)         cell.detailTextLabel?.text = thisRecord.pubDate.substring(from: index)     } 
like image 548
Raffaele Spadaro Avatar asked Sep 21 '17 06:09

Raffaele Spadaro


People also ask

How do you slice a string in Swift?

In Swift 4 you slice a string into a substring using subscripting. The use of substring(from:) , substring(to:) and substring(with:) are all deprecated.

What is substring Swift?

Substrings. When you get a substring from a string—for example, using a subscript or a method like prefix(_:) —the result is an instance of Substring , not another string. Substrings in Swift have most of the same methods as strings, which means you can work with substrings the same way you work with strings.

How do you get the first character of a string in Swift 5?

In Swift, the first property is used to return the first character of a string.

How do I remove the first character from a string in Swift?

Swift String dropFirst() The dropFirst() method removes the first character of the string.


1 Answers

Follow the below example to fix this warning: Supporting examples for Swift 3, 4 and 5.

let testStr = “Test Teja”  let finalStr = testStr.substring(to: index) // Swift 3 let finalStr = String(testStr[..<index]) // Swift 4  let finalStr = testStr.substring(from: index) // Swift 3 let finalStr = String(testStr[index...]) // Swift 4   //Swift 3 let finalStr = testStr.substring(from: index(startIndex, offsetBy: 3))   //Swift 4 and 5 let reqIndex = testStr.index(testStr.startIndex, offsetBy: 3) let finalStr = String(testStr[..<reqIndex])  //**Swift 5.1.3 - usage of index**  let myStr = "Test Teja == iOS"  let startBound1 = String.Index(utf16Offset: 13, in: myStr) let finalStr1 = String(myStr[startBound1...])// "iOS"  let startBound2 = String.Index(utf16Offset: 5, in: myStr) let finalStr2 = String(myStr[startBound2..<myStr.endIndex]) //"Teja == iOS" 
like image 183
Teja Kumar Bethina Avatar answered Oct 09 '22 15:10

Teja Kumar Bethina