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.
In swift, we can use the firstIndex(of:) method to get the index position of a character in a given string.
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.
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.
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With