In Objective-C I used:
[@"abc def ghi abc def ghi" rangeOfString:@"c" options:NSBackwardsSearch];
But now NSBackWardsSearch seems not to exist. Could anyone provide equivalent code for Swift?
I would like to be able to find the character number in the whole string if possible. So in the example above it would return 3.
Swift 3.0:
And if you want to replace the last substring in a string:
(Swift 3)
Usage:
Or, if you want to remove the last substring completely, and clean it up:
Cocoa frameworks should be accessible in Swift, but you need to import them. Try importing
Foundation
to access the NSString API. From "Working with Cocoa Data Types–Strings" of the "Using Swift with Cocoa and Objective-C" guide:Additionally,
NSBackwardsSearch
is an enum value (marked & imported as an option), so you have to use Swift's enum/option syntax to access it (as part of theNSStringCompareOptions
option type). Prefixes are stripped from C enumeration values, so drop theNS
from the value name.Taken all together, we have:
Note that you might have to use the
distance
andadvance
functions to properly make use of the range fromrangeOfString
.