#40: String Length in Swift

To get the length of a string in characters, use count:

let text = "Hello"
text.count // 5

This returns the number of extended grapheme clusters, which is what users normally perceive as characters.

If you need the UTF-8 or UTF-16 length instead, use the dedicated views:

text.utf8.count
text.utf16.count

Choose the version that matches your use case instead of assuming they are always identical.


I'm also on Twitter and GitHub.

Subscribe via RSS.