Swift 5: Index of a Character in String

2020-03-17 14:21发布

问题:

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:

After some time I have to admit that my original answer was incorrect.

In Swift are two methods: firstIndex(of:) and lastIndex(of:)

Both returns Int? representing index of first/last element in Array which is equal to passed element (if there is any, otherwise it returns nil).

So, you should avoid using your custom method to get index because there could be two same elements and you wouldn't know which index you need. So try to thing about your usage and decide which index is more suitable for you; first or last.