Characters in Swift


In Swift, a character is a data type that represents a single character. It is a kind of string literal that consists of only one character.

For example, “y”, “m”, “e” are examples of characters.

Character type literals can represent a character that can be made with one or more Unicode scalar values that are grouped by a Unicode boundary algorithm.

Characters are often used to represent Non-English languages, emojis and symbols.

Defining a character in Swift

Below is the syntax for creating a character:

var characterName: Character = SINGLE_CHARACTER_STRING

In Swift programming, we can create a character type variable using the Character keyword:

// Defining a character
var myChar: Character = "m"
print(myChar)

Output:

m

You can also define a character with a constant using the let keyword:

let myChar: Character = "m"

Creating an empty character

In Swift, it is not possible to create an empty character. It is not allowed.

If you try to create an empty character in Swift, the compiler will show an error.

Let’s see what happens if you try to create an empty character:

var emptyChar: Character = ""
print(emptyChar)

Running the above code will give the output with the error:

error: CodeSpeedy.playground:1:28: error: cannot convert value of type 'String' to specified type 'Character'
var emptyChar: Character = ""

Accessing characters of a string

A string is basically the collection of characters organized in a specific order. You can get iterate through the characters of a string to get each character of the string.

Using the for-in loop, you can easily access individual characters from a string with the same order as the string is. Below is the Swift program to iterate through the characters of a string to get the characters:

for singleChar in "Hello World" {
   print(singleChar)
}

We can also store the string in the variable and use the for-in loop:

var myString = "Hello World"

for singleChar in myString {
   print(singleChar)
}

Both of the codes, work in the same way. They both will show the output given below:

H
e
l
l
o

W
o
r
l
d

Store emoji in Swift character

In Swift, a Unicode also behave as a single character in character type literal. So we can store a specific emoji by providing its Unicode.

For example, below we are printing the flag of the United States:

var countryFlag = "\u{1F1FA}\u{1F1F8}"
print(countryFlag)

Output:

πŸ‡ΊπŸ‡Έ

Below is another example of creating a character type variable that stores a Unicode of Sparkling Heart:

var sparklingHeart: Character = "\u{1F496}"
print(sparklingHeart)

Output:

πŸ’–

After we print the character, we can see the emoji instead of the Unicode.