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?
It is much more simple than any of the answers here, once you find the right syntax.
I want to take away the [ and ]
result will be "ABCDEFGHI" the startIndex and endIndex could also be used in
and so on!
PS: As indicated in the remarks, there are some syntax changes in swift 2 which comes with xcode 7 and iOS9!
Please look at this page
You can use this extensions to improve
substringWithRange
Swift 2.3
Swift 3
Usage:
Swift 2
Simple
Swift 3
Swift 4
substring(to:)
andsubstring(from:)
are deprecated inSwift 4
.Rob Napier had already given a awesome answer using subscript. But i felt one drawback in that as there is no check for out of bound conditions. This can tend to crash. So i modified the extension and here it is
Output below
So i suggest always to check for the if let
In Swift3
For ex: a variable "Duke James Thomas", we need to get "James".
You can use any of the substring methods in a Swift String extension I wrote https://bit.ly/JString.