1

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.

bjornte
  • 749
  • 1
  • 9
  • 31
  • You should describe what it does also in the question. – Rakesha Shastri Nov 29 '18 at 11:38
  • https://stackoverflow.com/a/38215613/2303865 – Leo Dabus Nov 29 '18 at 11:44
  • You really don't need to include the answer to your question in the question itself. In fact, you probably shouldn't. That aside, and aside from this being a duplicate, this was a well-written question. Thank you for putting in the effort to actually ask something good. – Nic Nov 30 '18 at 01:27

0 Answers0