Swift 5: Index of a Character in String

Deadly 提交于 2019-12-01 03:46:48

问题


Before Swift 5, I had this extension working:

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

Now, I get a deprecated message:

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

Is there a simpler solution to this instead of using utf16Offset(in:)?

I just need the index of the character position passed back as an Int.


回答1:


And what is wrong with utf16Offset(in:)? This is way to go with Swift 5

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


来源:https://stackoverflow.com/questions/55384721/swift-5-index-of-a-character-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!