Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 5: Index of a Character in String

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.

like image 239
Gizmodo Avatar asked Mar 27 '19 19:03

Gizmodo


People also ask

How do you get the index of a character in a string in Swift?

In swift, we can use the firstIndex(of:) method to get the index position of a character in a given string.

How do you slice a string in Swift?

In Swift 4 you slice a string into a substring using subscripting. The use of substring(from:) , substring(to:) and substring(with:) are all deprecated.

What is startIndex in Swift?

The startIndex property of a string in Swift returns the position of the first character of a given string. This property only works if the string is not empty.


1 Answers

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. 🙏


Original answer:

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)
    }
}
like image 198
Robert Dresler Avatar answered Oct 11 '22 23:10

Robert Dresler