I have a string "hi @π ". if I check length of this string it comes 6. If I write string.characters[5] getting array index out of bound exception.Why ?? How to extract π .?
to check the length I am using string.utf16.count.
You get the error due to the fact that emojis are represented as Unicode characters, which don't necessarily have a length of 1, so you should always use indexes obtained from .index(of:) function to access characters of a string that contains emojis.
Have a look at this playground snippet, which shows you how to get emojis out of Strings safely.
let s = "hi @π , bye βοΈ asd"
s.characters.count
s.characters.index(of: "π")
if let emojiIndex = s.characters.index(of: "π") {
s[emojiIndex]
}
s.characters.index(of: "βοΈ")
if let emojiIndex = s.characters.index(of: "βοΈ") {
s[emojiIndex]
}
U get length of utf16 string
so if you want do smth like: string.characters[5]
do like string.utf16.characters[5]
let str = "ππ©βπ§βπ§π¨π¦", the output of str.utf16.count is 14, not 3.
string.utf16.countis different fromstring.characters.count