1

I am trying to get a substring from a string using the range without luck. Having searched high and low, I can't find a way to do this seemingly straightforward task in Swift. The range is in the form of an NSRange obtained from a delegate method.

In Objective-c, if you have a range, you could do:

NSString * text = "Hello World";
NSString *sub = [text substringWithRange:range];

According to this answer, the following should work in Swift:

let mySubstring = text[range]  // play
let myString = String(mySubstring)

However, when I try this, I get an error:

Cannot subscript a value of type 'String' with an index of type 'NSRange' (aka '_NSRange')

I think the issue may have to do with using an NSRange instead of a range but I can't figure out how to get it to work. Thanks for any suggestions.

zztop
  • 701
  • 1
  • 7
  • 20

2 Answers2

4

The thing is you can not subscript a String using a NSRange, you have to use a Range. Try the following out:

let newRange = Range(range, in: text)
let mySubstring = text[newRange]
let myString = String(mySubstring)
alanpaivaa
  • 1,959
  • 1
  • 14
  • 23
2

Please read your linked question one more time.

You will notice that String in Swift doesn't work with Range<Int> but with Range<String.Index> and definitely not with NSRange

Example of using range on string:

let text = "Hello world"
let from = text.index(after: text.startIndex)
let to = text.index(from, offsetBy: 4)
text[from...to] // ello
ManWithBear
  • 2,787
  • 15
  • 27