Search code examples
iosswiftrangesubstringnsrange

Return substring from attributed string using range in Swift


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.


Solution

  • 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)