从字符串中的字符集中查找最后一次出现的字符的索引

Find index of last occurrence of a character from character-set in string

有没有一种简便的方法可以找到属于给定字符集的字符串中最后一个字符的索引?

所以对于字符串"abcd123gws"和字符集"1234567890",结果应该是6:数字3.

这是一个可能的解决方案:

let input = "abcd123gws"
let characters = Set("1234567890")

if let lastOccurrenceIndex = input.lastIndex(where: characters.contains) {
    let result = input.distance(from: input.startIndex, to: lastOccurrenceIndex)
    print(result) // 6
}

正如@LeoDabus 在评论中建议的那样,如果您的字符集只包含数字,您可以使用 \.isWholeNumber(不需要单独的 Set):

if let lastOccurrenceIndex = input.lastIndex(where: \.isWholeNumber) { ... }