Character and String Data Types
Explore the use of Swift String and Character data types, including the use of Unicode and special characters. Also, learn how to build strings from multiple variables using string interpolation.
Character data type
The Swift Character
data type is used to store a single character of rendered text such as a letter, numerical digit, punctuation mark, or symbol. Internally, characters in Swift are stored in the form of grapheme clusters. A grapheme cluster is made of two or more Unicode scalars that are combined to represent a single visible character.
The following lines assign a variety of different characters to Character
type variables:
var myChar1: Character = "f"var myChar2: Character = ":"var myChar3: Character = "X"print(myChar1, myChar2, myChar3)
Note: If a single character is assigned to a constant or variable using type inference, the compiler will infer that the value is of type
String
instead ofCharacter
. If you specifically need the constant or variable to be of typeCharacter
you must declare it as such using type annotation.
Characters may also be referenced using Unicode code points. The following example assigns a star symbol to a variable using Unicode, and then prints it:
var myChar4: Character = "\u{2605}"print(myChar4)
String data type
The String
data type is a sequence of characters that typically make up a word or sentence. In addition to ...