Peter Silie Peter Silie - 4 months ago 91
Swift Question

Swift 3: String search backwards

I want to search backwards in a string. But all examples I found are not running on current Swift 3.0. ".BackwardsSearch" is not an option available on my XCode 8. Any idea, how this can be done?

let rPos = rIndex(sourceString, searchString)


let rPos = sourceString.rindex(of: searchString)


XCode autocomplete will suggest this:

let rpos = sourceString.range(of:searchString, options:String.CompareOptions.backwards, range:nil, locale:nil)

However, range and locale have defaults of nil, so you can omit them:

let rpos = sourceString.range(of:searchString, options:String.CompareOptions.backwards)

And options is of the type String.CompareOptions so you only need the last part:

let rpos = sourceString.range(of:searchString, options:.backwards)

(Thanks @MartinR for pointing out the shortened versions)