17

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.
JDev
  • 5,168
  • 6
  • 40
  • 61
  • are you sure it makes sense to be mutating a variable, rather than defining a new one? If the url is "clean" after taking off the last symbol, why is it called "cleanURL" even before then? – Alexander Aug 13 '17 at 17:17
  • 1
    Check [this thread](https://stackoverflow.com/q/45562662/6541007). Seems to be a duplicate. – OOPer Aug 13 '17 at 17:18

1 Answers1

31

Well, do what the error says, use the String slicing subscript (subscript(_:)) with a 'partial range upto' operator (..<, docs, where it's called a 'half open range', oddly enough):

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.

Alexander
  • 59,041
  • 12
  • 98
  • 151