Index(encodedOffset:) 有什么作用以及如何替换它?

What does Index(encodedOffset:) do and how do I replace it?

我使用的代码抛出以下错误:

'init(encodedOffset:)' is deprecated: encodedOffset has been deprecated as most common usage is incorrect. Use String.Index(utf16Offset:in:) to achieve the same behavior.

这实际上有什么作用,我该如何替换它?有没有更简单的方法来实现这种字符串格式?

extension String {
    func applyPatternOnNumbers(pattern: String, replacmentCharacter: Character) -> String {
        var pureNumber = self.replacingOccurrences( of: "[^0-9]", with: "", options: .regularExpression)
        for index in 0 ..< pattern.count {
            guard index < pureNumber.count else { return pureNumber }
            let stringIndex = String.Index(encodedOffset: index)
            let patternCharacter = pattern[stringIndex]
            guard patternCharacter != replacmentCharacter else { continue }
            pureNumber.insert(patternCharacter, at: stringIndex)
        }
        return pureNumber
    }
}

String.Index(encodedOffset:)Int 索引转换为 String.Index 索引。

建议的替换很简单

let stringIndex = String.Index(utf16Offset: index, in: pattern)

但是把Int转换成String.Index来回比较麻烦

这仅使用 String.Index

extension String {
    func applyPatternOnNumbers(pattern: String, replacmentCharacter: Character) -> String {
        var pureNumber = self.replacingOccurrences( of: "[^0-9]", with: "", options: .regularExpression)
        for index in pattern.indices {
            guard index < pureNumber.endIndex else { return pureNumber }
            let patternCharacter = pattern[index]
            guard patternCharacter != replacmentCharacter else { continue }
            pureNumber.insert(patternCharacter, at: index)
        }
        return pureNumber
    }
}