Enix Enix - 9 months ago 49
Swift Question

Swift 2/3 String implement of rindexOf method

I know there is an build in method to get the index of substring from the original string by using

. But it is used to get the first occurrence of a given substring. However what I need to do is to get the last occurrence of the given substring.

This is something like the
in python language

So, my question is, How can I do that in Swift 2.x/3? A code snippet example is appreciated.


You are close. Try the below, adding the optional options parameter and searching the string from the back instead.

let myString = "testingteststring"
let lastSubstringRange = myString.range(of: "test", options: String.CompareOptions.backwards)

'lastSubstringRange' will be the range of the last 'test' substring in 'myString'. For more info, try looking at Apple Developer: https://developer.apple.com/reference/swift/string/1642786-range