Reputation: 3369
Say I have a string:
NSString *state = @"California, CA";
Can someone please tell me how to extract the last two characters from this string (@"CA"
in this example).
Upvotes: 52
Views: 47304
Reputation: 1817
Just simply add this extension and use it for String types:
extension String {
var last2: String {
String(self.suffix(2))
}
}
Upvotes: 1
Reputation: 12363
Swift 4:
let code = (state as? NSString)?.substring(from: state.characters.count - 2)
Upvotes: 0
Reputation: 100648
NSString *code = [state substringFromIndex: [state length] - 2];
should do it
Upvotes: 156