Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? Example:

let rPos = rIndex(sourceString, searchString)

or

let rPos = sourceString.rindex(of: searchString)
like image 900
Peter Silie Avatar asked Sep 22 '16 12:09

Peter Silie


1 Answers

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)

like image 139
DavidA Avatar answered Oct 23 '22 21:10

DavidA