Characters and strings

The Character data type can store a single character. For example:

let characterA: Character = "a"

This stores the character a. It can hold any character — even an emoji:

But this data type is designed to hold only single characters. The String data type, on the other hand, stores multiple characters. For example:

let stringDog: String = "Dog"

It’s as simple as that! The right-hand side of this expression is what’s known as a

string literal; it’s the Swift syntax for representing a string.

Of course, type inference applies here as well. If you remove the type in the above declaration, then Swift does the right thing and makes the stringDog a String constant:

let stringDog = "Dog" // Inferred to be of type String

Note: There’s no such thing as a character literal in Swift. A character is simply a string of length one. However, Swift infers the type of any string literal to be String, so if you want a Character instead, you must make the type explicit.

results matching ""

    No results matching ""