Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

Tags:

swift

I have not yet been able to figure out how to get a substring of a String in Swift:

var str = “Hello, playground” func test(str: String) -> String {  return str.substringWithRange( /* What goes here? */ ) } test (str) 

I'm not able to create a Range in Swift. Autocomplete in the Playground isn’t super helpful - this is what it suggests:

return str.substringWithRange(aRange: Range<String.Index>) 

I haven't found anything in the Swift Standard Reference Library that helps. Here was another wild guess:

return str.substringWithRange(Range(0, 1)) 

And this:

let r:Range<String.Index> = Range<String.Index>(start: 0, end: 2) return str.substringWithRange(r) 

I've seen other answers (Finding index of character in Swift String) that seem to suggest that since String is a bridge type for NSString, the "old" methods should work, but it's not clear how - e.g., this doesn't work either (doesn't appear to be valid syntax):

let x = str.substringWithRange(NSMakeRange(0, 3)) 

Thoughts?

like image 861
Rob Avatar asked Jun 04 '14 18:06

Rob


People also ask

How does range work in Swift?

Ranges in Swift allow us to select parts of Strings, collections, and other types. They're the Swift variant of NSRange which we know from Objective-C although they're not exactly the same in usage, as I'll explain in this blog post. Ranges allow us to write elegant Swift code by making use of the range operator.

What is range of string?

string range string first last. Returns a range of consecutive characters from string, starting with the character whose index is first and ending with the character whose index is last. An index of 0 refers to the first character of the string. first and last may be specified as for the index method.


1 Answers

You can use the substringWithRange method. 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" 

To change the start and end index, use advancedBy(n).

var str = "Hello, playground" str.substringWithRange(Range<String.Index>(start: str.startIndex.advancedBy(2), end: str.endIndex.advancedBy(-1))) //"llo, playgroun" 

You can also still use the NSString 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)) 

Note: as JanX2 mentioned, this second method is not safe with unicode strings.

like image 121
Connor Avatar answered Sep 23 '22 19:09

Connor