Structure

Character

A single extended grapheme cluster, which approximates a user-perceived character.

Overview

The Character type represents a character made up of one or more Unicode scalar values, grouped by a Unicode boundary algorithm. Generally, a Character instance matches what the reader of a string will perceive as a single character. The number of visible characters is generally the most natural way to count the length of a string.

let greeting = "Hello! 🐥"
print("Character count: \(greeting.characters.count)")
// Prints "Character count: 8"

Because each character in a string can be made up of one or more Unicode code points, the number of characters in a string may not match the length of the Unicode code point representation or the length of the string in a particular binary representation.

print("Unicode code point count: \(greeting.unicodeScalars.count)")
// Prints "Unicode code point count: 15"

print("UTF-8 representation count: \(greeting.utf8.count)")
// Prints "UTF-8 representation count: 18"

Every Character instance is composed of one or more Unicode code points that are grouped together as an extended grapheme cluster. The way these code points are grouped is defined by a canonical, localized, or otherwise tailored Unicode segmentation algorithm.

For example, a country’s Unicode flag character is made up of two regional indicator code points that correspond to that country’s ISO 3166-1 alpha-2 code. The alpha-2 code for The United States is “US”, so its flag character is made up of the Unicode code points "\u{1F1FA}" (REGIONAL INDICATOR SYMBOL LETTER U) and "\u{1F1F8}" (REGIONAL INDICATOR SYMBOL LETTER S). When placed next to each other in a Swift string literal, these two code points are combined into a single grapheme cluster, represented by a Character instance in Swift.

let usFlag: Character = "\u{1F1FA}\u{1F1F8}"
print(usFlag)
// Prints "🇺🇸"

For more information about the Unicode terms used in this discussion, see the Unicode.org glossary. In particular, this discussion mentions extended grapheme clusters and Unicode scalar values.

Symbols

Initializers

init(UnicodeScalar)

Creates a character containing the given Unicode scalar value.

init(String)

Creates a character from a single-character string.

init(extendedGraphemeClusterLiteral: Character)

Creates a character with the specified value.

init(unicodeScalarLiteral: Character)

Creates a character with the specified value.

Instance Properties

var customMirror: Mirror

A mirror that reflects the Character instance.

var customPlaygroundQuickLook: PlaygroundQuickLook
var debugDescription: String

A textual representation of the character, suitable for debugging.

var description: String
var hashValue: Int

The character’s hash value.

Instance Methods

func write<Target>(to: inout Target)

Writes the character into the given output stream.