2

I am trying to convert Swift 3 code into Swift 4. But this error shows:

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

my code is :

extension String {

    func substring(_ from: Int) -> String {
        return self.substring(from: self.characters.index(self.startIndex, offsetBy: from))
    }

}
pkamb
  • 33,281
  • 23
  • 160
  • 191
Uday Babariya
  • 1,031
  • 1
  • 13
  • 31
  • See https://stackoverflow.com/questions/45562662/how-to-use-string-slicing-subscript-in-swift-4 – algrid Sep 02 '17 at 07:29
  • i already checked.... but still don't understand... can you please explain... @algrid – Uday Babariya Sep 02 '17 at 07:31
  • can you please explain @MoeAbdul-Hameed – Uday Babariya Sep 02 '17 at 07:33
  • @UdayBabariya Read this and you'll be fine. Let me know if you needed more details. https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html#//apple_ref/doc/uid/TP40014097-CH7-ID555 – Mo Abdul-Hameed Sep 02 '17 at 07:35

1 Answers1

6

You should have:

extension String {

    func substring(_ from: Int) -> String {
        let start = index(startIndex, offsetBy: from)
        return String(self[start ..< endIndex])
    }
}

In swift you can get a substring using slicing - a construction like this: string[startIndex ..< endIndex]. String index is a special type in swift so you can't use simple ints - you have to get proper indexes for instance calling index(_,offsetBy:) or using predefined startIndex and endIndex.

algrid
  • 5,600
  • 3
  • 34
  • 37