0

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.

4
  • 2
    The emoji is at index 4. Commented Jun 8, 2017 at 13:05
  • why getting exception ? length is 6. I am trying to get the character at specific position. Commented Jun 8, 2017 at 13:12
  • The smiley face takes up 2 positions in the string (which is why the count is 6), but uses 1 character which is why it is at position 4. If you watch the WWDC 2017 video about whats new in Swift where they cover this. You can also read more about this here: developer.apple.com/library/content/documentation/Swift/… Commented Jun 8, 2017 at 13:23
  • The Emoji counts as a single character in Swift, but as two UTF-16 code units. Therefore string.utf16.count is different from string.characters.count Commented Jun 8, 2017 at 13:24

2 Answers 2

1

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]
}
Sign up to request clarification or add additional context in comments.

Comments

-2

U get length of utf16 string

so if you want do smth like: string.characters[5]

do like string.utf16.characters[5]

1 Comment

This fails for many Emoji and other characters. For example, the string let str = "πŸπŸ‘©β€πŸ‘§β€πŸ‘§πŸ‡¨πŸ‡¦", the output of str.utf16.count is 14, not 3.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.