Calculate the size in bytes of a Swift string

I am trying to calculate the size in String bytes in Swift, but I do not know what character size is; how many bytes are encoded?

Say I have a line: let str = "hello, world"

I want to send this to my server, but my server will only accept strings under 32 bytes. How can I control the length of my string?

+5
source share
1 answer

It all depends on the character encoding, let UTF8:

 let string = "abde" let size = string.utf8.count 

Note that not all characters have the same byte size in UTF8. If your string is ASCII, you can assume 1 byte per character.

+6
source

All Articles