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?
First create the range, then the substring. You can use
fromIndex..<toIndex
syntax like so:http://www.learnswiftonline.com/reference-guides/string-reference-guide-for-swift/ shows that this works well:
Updated for Xcode 7. Adds String extension:
Use:
Implementation:
At the time I'm writing, no extension is perfectly Swift 3 compatible, so here is one that covers all the needs I could think of:
And then, you can use:
string.substring(from: 1, to: 7)
gets you:ello,Wo
string.substring(to: 7)
gets you:Hello,Wo
string.substring(from: 3)
gets you:lo,World!
string.substring(from: 1, length: 4)
gets you:ello
string.substring(length: 4, to: 7)
gets you:o,Wo
Updated
substring(from: Int?, length: Int)
to support starting from zero.Well, I had the same issue and solved with the "bridgeToObjectiveC()" function:
Please note that in the example, substringWithRange in conjunction with NSMakeRange take the part of the string starting at index 6 (character "W") and finishing at index 6 + 6 positions ahead (character "!")
Cheers.
In new Xcode 7.0 use