If I want to extract parts of a string in Swift 4 (when building a Mac app in Xcode 10), are there less convoluted ways of extracting said parts? The code below works, but to me it's nearly unreadable.
let myString = "foobar"
let myShorterString = String(myString[myString.index(myString.startIndex, offsetBy: 2)..<myString.index(myString.startIndex, offsetBy: 5)])
I want to end up with oba
in this case.
Some documentation claims that "foobar"[2...5]
should work, but to me that throws the error cannot subscript String with an integer range
. Also, 'substring(to:)' has reportedly been deprecated.
I am aware of Leo Dabus' thorough answer, but even though that seems prudent, it has approx. 60 lines of code, so I think of that as more convoluted. I'm looking for less convoluted answers, and if there are none, confirmation that this is the simplest solution.
Answer:
let myShorterString = String(Array(myString)[2...4])
Courtesy of Harsh G.'s answer.