Swift 4: 'substring(to:)' is deprecated

Justin Bush picture Justin Bush · Aug 13, 2017 · Viewed 12.1k times · Source

I'm having trouble converting my Swift 3 code to Swift 4. I've managed to translate everything else in the app successfully, but am having trouble with a single line of code:

cleanURL = cleanURL.substring(to: cleanURL.index(before: cleanURL.endIndex))

The error I'm getting is this:

ViewController.swift:62:33: 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range upto' operator.

Answer

Alexander picture Alexander · Aug 13, 2017

Well, do what the error says,use String slicing subscript with a 'partial range upto' operator:

let actuallyCleanURL = kindaCleanURL[..<kindaCleanURL.endIndex]

Note that this returns a Substring. If you need to do more slicing operations, do them on this substring. Once you're done, promote your to a String by running it through the String initializer (String(mySubString)), causing a copy of the memory to be made.