Swift - Data Type String Length

Introduction

There are two ways to find the length of a string in Swift:

  • Use the equivalent of the length property in Swift. It is useful if you are not dealing with Unicode characters in your string.
  • Use the global countElements () function available in Swift to count the length/size of a string. The countElements () function counts the size of Unicode characters correctly.
let bouquet:Character = "\u{1F490}"

Because bouquet is declared as a Character, you will not be able to use the countElements() function.

The countElements() function only works for strings.

print(countElements(bouquet))  //error

The following statements each output 1 for the length of the strings:

Demo

var s1 = "e"                 
print(countElements(s1))   //  w  w  w. ja v  a  2s . c  o m
var s2 = "\u{E9}"            
print(countElements(s2))

Whether you use a Unicode character directly or use a Unicode scalar within your string, the length of the string is still the same:

Demo

var s3 = "cafe"              
print(countElements(s3))   /*from   w w w . j  a v a  2s  .c  o m*/

var s4 = "caf\u{E9}"         
print(countElements(s4))

Even if you combine a Unicode scalar with a string, the countElements() function will still count the number of characters:

Demo

var s5 = "voila"             
print(countElements(s5))   //from ww w  . j  a v  a 2s  .co m

var s6 = "voila" + "\u{300}" 
print(countElements(s6))

Related Topic