8

在 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 传回的字符位置的索引。

4

1 回答 1

11

一段时间后,我不得不承认我原来的答案是不正确的。

在 Swift 中有两种方法:firstIndex(of:)lastIndex(of:)

两者都返回Int?表示第一个/最后一个元素的索引,Array其中等于传递的元素(如果有,则返回nil)。

因此,您应该避免使用自定义方法来获取索引,因为可能有两个相同的元素并且您不知道需要哪个索引。因此,请尝试了解您的使用情况并确定哪个索引更适合您;第一个或最后一个。


原答案:

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

fileprivate extension String {
    func indexOf(char: Character) -> Int? {
        return firstIndex(of: char)?.utf16Offset(in: self)
    }
}
于 2019-03-27T19:05:44.393 回答