13

I have this String category:

extension String {

    subscript (i: Int) -> String {
        return self[Range(i ..< i + 1)]
    }

    subscript (r: Range<Int>) -> String {
        let range = Range(uncheckedBounds: (lower: max(0, min(count, r.lowerBound)),
                                            upper: min(count, max(0, r.upperBound))))
        let start = index(startIndex, offsetBy: range.lowerBound)
        let end = index(start, offsetBy: range.upperBound - range.lowerBound)
        return String(self[start ..< end])
    }
}

and Xcode is giving me a warning at this line: return self[Range(i ..< i + 1)]

'init' is deprecated: CountableRange is now Range. No need to convert any more.

It's a shame that even though I'm quite well experienced with Swift, I have no idea how to fix this. Question is: how to get rid of this warning.

Thank you!

Glenn Posadas
  • 12,555
  • 6
  • 54
  • 95
  • @MartinR - That doesn't seem to be a duplicate. It's a different error and a different code change. Am I missing something? – rmaddy Oct 05 '18 at 05:22
  • It looked like the same problem to me (CountableRange is not a separate type anymore, and the conversion method has been removed), and the same solution: Replacing `Range(i ..< i + 1)` by `i.. – Martin R Oct 05 '18 at 05:25
  • @MartinR OK, after another look, I see the code change is the same. But given the error messages are so different, this is still a good question even if the solution ends of being the same as the other one. – rmaddy Oct 05 '18 at 05:30
  • @rmaddy: Please feel free to reopen the thread if you find it appropriate. (A reference to the other Q&A might still be useful because it explains where the problem comes from.) – Martin R Oct 05 '18 at 05:31

1 Answers1

20

You don't need the Range.init. In other words, change:

return self[Range(i ..< i + 1)]

to:

return self[i ..< i + 1]
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Okay, thank you. Before I saw your answer, I was reading this (https://useyourloaf.com/blog/updating-strings-for-swift-4/), and tried that code above, and it worked. Will mark this as an answer in 10 mins. – Glenn Posadas Oct 05 '18 at 05:20