How to use String.substringWithRange in Swift? Or how do Ranges work in Swift?
Hi everyone! I'm new to Swift, transitioning from Objective-C, and I'm having trouble working with strings. In Objective-C, I easily extracted substrings using `substringWithRange:`, for example:
```objc
NSString *str = @"Hello, world!";
NSRange range = NSMakeRange(0, 5);
NSString *substr = [str substringWithRange:range]; // "Hello"
```
In Swift, I'm trying to do the same thing but encountering errors. I wrote:
```swift
let str = "Hello, world!"
let range = NSMakeRange(0, 5)
let substr = str.substringWithRange(range) // Error!
```
Xcode says that `String` doesn't have a `substringWithRange` method. I've read that in Swift you need to use `Range`, but I don't understand how to create it. Why can't I just pass an `NSRange`?
Please explain with examples:
1.
No answers yet.
Log in to leave an answer