Well first of all, youYou can still use the NSStringsubstringWithRange method with NSRange, but you have to make sure you are using an NSString like this:
let myNSString = str as NSString myNSString.substringWithRange(NSRange(location: 0,length: 3))
I've had trouble with using Ranges on Swift strings as well. This is the best I've come up with:It takes a start and end String.Index.
var str = "Hello, playground" str.substringWithRange(Range<String.Index>(start: str.startIndex, end: str.endIndex)) //"Hello, playground"
It runs fine, but I haven't figured out how use indices other thanTo change the start and end.
There is a succ() and pred() method on String.Index which returns the index before or after itself, but they don't take any arguments so it seems like there's no easy way to select different indicesuse advance().
var str = "Hello, playground" str.substringWithRange(Range<String.Index>(start: advance(str.startIndex.succ().succ(, 2), end: advance(str.endIndex, -1))) // "llo, Playground"playgroun"
Here'sYou can also still use the definition of String.IndexNSString method with NSRange, but you have to make sure you are using an NSString like this:
extension String : Collection { let structmyNSString Index= :str BidirectionalIndexas {NSString func succ() -> StringmyNSString.Index func predsubstringWithRange() -> String.Index } var startIndex: String.Index { get } var endIndexNSRange(location: String.Index { get } subscript0, (ilength: String.Index3) -> Character { get } func generate() -> IndexingGenerator<String> }
Note: as JanX2 mentioned, this method is not safe with unicode strings.