Just access back
The best way is to use substringToIndex combination with the endIndex property and the global advance function.
var string1 = "www.stackoverflow.com" var index1 = advance(string1.endIndex, -4) var substring1 = string1.substringToIndex(index1)
I am looking for a line starting from the back
Use rangeOfString and set options to .BackwardsSearch
var string2 = "www.stackoverflow.com" var index2 = string2.rangeOfString(".", options: .BackwardsSearch)?.startIndex var substring2 = string2.substringToIndex(index2!)
No extensions, pure idiomatic Swift
Swift 2.0
advance now part of Index and is called advancedBy . You do it like:
var string1 = "www.stackoverflow.com" var index1 = string1.endIndex.advancedBy(-4) var substring1 = string1.substringToIndex(index1)
Swift 3.0
You cannot call advancedBy on a String because it has elements of variable size. You should use index(_, offsetBy:) .
var string1 = "www.stackoverflow.com" var index1 = string1.index(string1.endIndex, offsetBy: -4) var substring1 = string1.substring(to: index1)
Much has been renamed. Cases are written in CamelCase, startIndex became lowerBound .
var string2 = "www.stackoverflow.com" var index2 = string2.range(of: ".", options: .backwards)?.lowerBound var substring2 = string2.substring(to: index2!)
Also, I would not recommend forced index2 . You can use optional binding or map . Personally, I prefer to use map :
var substring3 = index2.map(string2.substring(to:))
Swift 4
The Swift 3 version is still valid, but now you can use subscriptions with index ranges:
let string1 = "www.stackoverflow.com" let index1 = string1.index(string1.endIndex, offsetBy: -4) let substring1 = string1[..<index1]
The second approach remains unchanged:
let string2 = "www.stackoverflow.com" let index2 = string2.range(of: ".", options: .backwards)?.lowerBound let substring3 = index2.map(string2.substring(to:))