๐ŸŽ“ A1Learner
๐Ÿ”

Swift Characters

A Character is a value that holds exactly one single character. A string is built from characters placed in order.

One character in a Character value

The annotation after the colon names the Character type. The stored value is exactly one character, and the print shows it.

let letter: Character = "x"
print(letter)

Counting characters in a string

The count of a string counts its characters one by one. A space inside the string counts as a character too.

let word = "hi there"
print(word.count)

An emoji is one character

A flag symbol looks like two letters joined together. Its count shows it is a single character.

print("๐Ÿ‡ฎ๐Ÿ‡ณ".count)

The first character

startIndex names the position of the first character. Square brackets read the character at that position.

let word = "Swift"
print(word[word.startIndex])

A number cannot index a string

Square brackets with a plain number do not work on a string. The program fails to compile with this error.

let word = "Swift"
print(word[0])

Example

let initial: Character = "A"
let city = "Agra"
print(initial)
print(city.count)
print(city[city.startIndex])

Key points

  • Use a type annotation to store one character as a Character value.
  • The count of a string gives how many characters the string holds.
  • One visible symbol can be a single character even when it looks wide.
  • Use word[word.startIndex] to read the first character of a string named word.

In this example, initial holds the single character A and city holds the string Agra. The first print shows A. The second print shows 4, the count of characters in Agra. The third print reads the character at startIndex and shows A again.

Note

Writing word[0] for a string fails to compile.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

A program prints "cat".count. What prints?