Swift 5:字符串中字符的索引

问题描述 投票:2回答:1

在Swift 5之前,我有这个扩展工作:

  fileprivate extension String {
        func indexOf(char: Character) -> Int? {
            return firstIndex(of: char)?.encodedOffset
        }
    }

现在,我收到一条弃用的消息:

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

有没有更简单的解决方案,而不是使用utf16Offset(in:)

我只需要作为Int传回的字符位置的索引。

swift string indexof swift5
1个回答
5
投票

utf16Offset(in:)有什么问题?这是Swift 5的方法

fileprivate extension String {
    func indexOf(char: Character) -> Int? {
        return firstIndex(of: char)?.utf16Offset(in: self)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.