Character

struct Character

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

Inheritance Comparable, CustomDebugStringConvertible, CustomReflectable, CustomStringConvertible, Equatable, ExpressibleByExtendedGraphemeClusterLiteral, Hashable, TextOutputStreamable
Associated Types
public typealias UTF8View = String.UTF8View
public typealias UTF16View = String.UTF16View
public typealias UnicodeScalarView = String.UnicodeScalarView

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. Strings are collections of Character instances, so the number of visible characters is generally the most natural way to count the length of a string.

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

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

print("Unicode scalar value count: \(greeting.unicodeScalars.count)")
// Prints "Unicode scalar value 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 scalar values that are grouped together as an extended grapheme cluster. The way these scalar values 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 scalar values 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 scalar values "\u{1F1FA}" (REGIONAL INDICATOR SYMBOL LETTER U) and "\u{1F1F8}" (REGIONAL INDICATOR SYMBOL LETTER S). When placed next to each other in a string literal, these two scalar values 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.

Initializers

init init(_:) Required

Creates a character containing the given Unicode scalar value.

  • Parameter content: The Unicode scalar value to convert into a character.

Declaration

@inlinable public init(_ content: Unicode.Scalar)
init init(_:) Required

Creates a character from a single-character string.

The following example creates a new character from the uppercase version of a string that only holds one character.

let a = "a"
let capitalA = Character(a.uppercased())
  • Parameter s: The single-character string to convert to a Character instance. s must contain exactly one extended grapheme cluster.

Declaration

@inlinable public init(_ s: String)
init init(extendedGraphemeClusterLiteral:) Required

Creates a character with the specified value.

Do not call this initalizer directly. It is used by the compiler when you use a string literal to initialize a Character instance. For example:

let oBreve: Character = "o\u{306}"
print(oBreve)
// Prints "ŏ"

The assignment to the oBreve constant calls this initializer behind the scenes.

Declaration

@inlinable public init(extendedGraphemeClusterLiteral value: Character)

Instance Variables

var asciiValue Required

The ASCII encoding value of this character, if it is an ASCII character.

let chars: [Character] = ["a", " ", "™"]
for ch in chars {
    print(ch, "-->", ch.properties.numericValue)
}
// a --> 97
//   --> 32
// ™ --> nil

A character with the value "\r\n" (CR-LF) is normalized to "\n" (LF) and has an asciiValue property equal to 10.

let cr = "\r" as Character
// cr.asciiValue == 13
let lf = "\n" as Character
// lf.asciiValue == 10
let crlf = "\r\n" as Character
// crlf.asciiValue == 10

Declaration

var asciiValue: UInt8?
var customMirror Required

A mirror that reflects the Character instance.

Declaration

var customMirror: Mirror
var customPlaygroundQuickLook Required

A custom playground Quick Look for the Character instance.

Declaration

var customPlaygroundQuickLook: _PlaygroundQuickLook
var debugDescription Required

A textual representation of the character, suitable for debugging.

Declaration

var debugDescription: String
var description Required

A textual representation of this instance.

Calling this property directly is discouraged. Instead, convert an instance of any type to a string by using the String(describing:) initializer. This initializer works with any type, and uses the custom description property for types that conform to CustomStringConvertible:

struct Point: CustomStringConvertible {
    let x: Int, y: Int

    var description: String {
        return "(\(x), \(y))"
    }
}

let p = Point(x: 21, y: 30)
let s = String(describing: p)
print(s)
// Prints "(21, 30)"

The conversion of p to a string in the assignment to s uses the Point type's description property.

Declaration

var description: String
var hexDigitValue Required

The numeric value this character represents, if it is a hexadecimal digit.

Hexadecimal digits include 0-9, Latin letters a-f and A-F, and their fullwidth compatibility forms. If the character does not represent a hexadecimal digit, the value of this property is nil.

let chars: [Character] = ["1", "a", "F", "g"]
for ch in chars {
    print(ch, "-->", ch.hexDigitValue)
}
// 1 --> 1
// a --> 10
// F --> 15
// g --> nil

Declaration

var hexDigitValue: Int?
var isASCII Required

A Boolean value indicating whether this is an ASCII character.

Declaration

var isASCII: Bool
var isCased Required

A Boolean value indicating whether this character changes under any form of case conversion.

Declaration

var isCased: Bool
var isCurrencySymbol Required

A Boolean value indicating whether this character represents a currency symbol.

For example, the following characters all represent currency symbols:

Declaration

var isCurrencySymbol: Bool
var isHexDigit Required

A Boolean value indicating whether this character represents a hexadecimal digit.

Hexadecimal digits include 0-9, Latin letters a-f and A-F, and their fullwidth compatibility forms. To get the character's value, use the hexDigitValue property.

Declaration

var isHexDigit: Bool
var isLetter Required

A Boolean value indicating whether this character is a letter.

For example, the following characters are all letters:

Declaration

var isLetter: Bool
var isLowercase Required

A Boolean value indicating whether this character is considered lowercase.

Lowercase characters change when converted to uppercase, but not when converted to lowercase. The following characters are all lowercase:

Declaration

var isLowercase: Bool
var isMathSymbol Required

A Boolean value indicating whether this character represents a symbol that naturally appears in mathematical contexts.

For example, the following characters all represent math symbols:

The set of characters that have an isMathSymbol value of true is not a strict subset of those for which isSymbol is true. This includes characters used both as letters and commonly in mathematical formulas. For example, "ϰ" (U+03F0 GREEK KAPPA SYMBOL) is considered both a mathematical symbol and a letter.

This property corresponds to the "Math" property in the Unicode Standard.

Declaration

var isMathSymbol: Bool
var isNewline Required

A Boolean value indicating whether this character represents a newline.

For example, the following characters all represent newlines:

  • U+000B: LINE TABULATION (VT)
  • U+000C: FORM FEED (FF)
  • U+0085: NEXT LINE (NEL)
  • U+2028: LINE SEPARATOR
  • U+2029: PARAGRAPH SEPARATOR

Declaration

var isNewline: Bool
var isNumber Required

A Boolean value indicating whether this character represents a number.

For example, the following characters all represent numbers:

Declaration

var isNumber: Bool
var isPunctuation Required

A Boolean value indicating whether this character represents punctuation.

For example, the following characters all represent punctuation:

Declaration

var isPunctuation: Bool
var isSymbol Required

A Boolean value indicating whether this character represents a symbol.

This property is true only for characters composed of scalars in the "Math_Symbol", "Currency_Symbol", "Modifier_Symbol", or "Other_Symbol" categories in the Unicode Standard.

For example, the following characters all represent symbols:

Declaration

var isSymbol: Bool
var isUppercase Required

A Boolean value indicating whether this character is considered uppercase.

Uppercase characters vary under case-conversion to lowercase, but not when converted to uppercase. The following characters are all uppercase:

Declaration

var isUppercase: Bool
var isWhitespace Required

A Boolean value indicating whether this character represents whitespace, including newlines.

For example, the following characters all represent whitespace:

Declaration

var isWhitespace: Bool
var isWholeNumber Required

A Boolean value indicating whether this character represents a whole number.

For example, the following characters all represent whole numbers:

Declaration

var isWholeNumber: Bool
var unicodeScalars Required

Declaration

var unicodeScalars: Character.UnicodeScalarView
var utf16 Required

A UTF-16 encoding of self.

Declaration

var utf16: Character.UTF16View
var utf8 Required

A UTF-8 encoding of self.

Declaration

var utf8: Character.UTF8View
var wholeNumberValue Required

The numeric value this character represents, if it represents a whole number.

If this character does not represent a whole number, or the value is too large to represent as an Int, the value of this property is nil.

let chars: [Character] = ["4", "④", "万", "a"]
for ch in chars {
    print(ch, "-->", ch.properties.numericValue)
}
// 4 --> 4
// ④ --> 4
// 万 --> 10000
// a --> nil

Declaration

var wholeNumberValue: Int?

Instance Methods

func hash(into hasher: inout Hasher) Required

Hashes the essential components of this value by feeding them into the given hasher.

  • Parameter hasher: The hasher to use when combining the components of this instance.

Declaration

public func hash(into hasher: inout Hasher)
func lowercased() -> String Required

Returns a lowercased version of this character.

Because case conversion can result in multiple characters, the result of lowercased() is a string.

let chars: [Character] = ["E", "É", "И", "Π", "1"]
for ch in chars {
    print(ch, "-->", ch.lowercased())
}
// E --> e
// É --> é
// И --> и
// Π --> π
// 1 --> 1

Declaration

public func lowercased() -> String
func uppercased() -> String Required

Returns an uppercased version of this character.

Because case conversion can result in multiple characters, the result of uppercased() is a string.

let chars: [Character] = ["e", "é", "и", "π", "ß", "1"]
for ch in chars {
    print(ch, "-->", ch.uppercased())
}
// e --> E
// é --> É
// и --> И
// π --> Π
// ß --> SS
// 1 --> 1

Declaration

public func uppercased() -> String
func write(to target: inout Target) Required

Writes the character into the given output stream.

  • Parameter target: An output stream.

Declaration

public func write<Target>(to target: inout Target) where Target: TextOutputStream

Type Methods

func !=(lhs: Self, rhs: Self) -> Bool Required

Declaration

public static func !=(lhs: Self, rhs: Self) -> Bool
func ...(maximum: Self) -> PartialRangeThrough<Self> Required

Returns a partial range up to, and including, its upper bound.

Use the prefix closed range operator (prefix ...) to create a partial range of any type that conforms to the Comparable protocol. This example creates a PartialRangeThrough<Double> instance that includes any value less than or equal to 5.0.

let throughFive = ...5.0

throughFive.contains(4.0)     // true
throughFive.contains(5.0)     // true
throughFive.contains(6.0)     // false

You can use this type of partial range of a collection's indices to represent the range from the start of the collection up to, and including, the partial range's upper bound.

let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[...3])
// Prints "[10, 20, 30, 40]"
  • Parameter maximum: The upper bound for the range.

Declaration

prefix public static func ...(maximum: Self) -> PartialRangeThrough<Self>
func ...(minimum: Self) -> PartialRangeFrom<Self> Required

Returns a partial range extending upward from a lower bound.

Use the postfix range operator (postfix ...) to create a partial range of any type that conforms to the Comparable protocol. This example creates a PartialRangeFrom<Double> instance that includes any value greater than or equal to 5.0.

let atLeastFive = 5.0...

atLeastFive.contains(4.0)     // false
atLeastFive.contains(5.0)     // true
atLeastFive.contains(6.0)     // true

You can use this type of partial range of a collection's indices to represent the range from the partial range's lower bound up to the end of the collection.

let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[3...])
// Prints "[40, 50, 60, 70]"
  • Parameter minimum: The lower bound for the range.

Declaration

postfix public static func ...(minimum: Self) -> PartialRangeFrom<Self>
func ...(minimum: Self, maximum: Self) -> ClosedRange<Self> Required

Returns a closed range that contains both of its bounds.

Use the closed range operator (...) to create a closed range of any type that conforms to the Comparable protocol. This example creates a ClosedRange<Character> from "a" up to, and including, "z".

let lowercase = "a"..."z"
print(lowercase.contains("z"))
// Prints "true"

Declaration

public static func ...(minimum: Self, maximum: Self) -> ClosedRange<Self>
func ..<(maximum: Self) -> PartialRangeUpTo<Self> Required

Returns a partial range up to, but not including, its upper bound.

Use the prefix half-open range operator (prefix ..<) to create a partial range of any type that conforms to the Comparable protocol. This example creates a PartialRangeUpTo<Double> instance that includes any value less than 5.0.

let upToFive = ..<5.0

upToFive.contains(3.14)       // true
upToFive.contains(6.28)       // false
upToFive.contains(5.0)        // false

You can use this type of partial range of a collection's indices to represent the range from the start of the collection up to, but not including, the partial range's upper bound.

let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[..<3])
// Prints "[10, 20, 30]"
  • Parameter maximum: The upper bound for the range.

Declaration

prefix public static func ..<(maximum: Self) -> PartialRangeUpTo<Self>
func ..<(minimum: Self, maximum: Self) -> Range<Self> Required

Returns a half-open range that contains its lower bound but not its upper bound.

Use the half-open range operator (..<) to create a range of any type that conforms to the Comparable protocol. This example creates a Range<Double> from zero up to, but not including, 5.0.

let lessThanFive = 0.0..<5.0
print(lessThanFive.contains(3.14))  // Prints "true"
print(lessThanFive.contains(5.0))   // Prints "false"

Declaration

public static func ..<(minimum: Self, maximum: Self) -> Range<Self>
func <(lhs: Character, rhs: Character) -> Bool Required

Returns a Boolean value indicating whether the value of the first argument is less than that of the second argument.

This function is the only requirement of the Comparable protocol. The remainder of the relational operator functions are implemented by the standard library for any type that conforms to Comparable.

Declaration

@inlinable public static func <(lhs: Character, rhs: Character) -> Bool
func <=(lhs: Self, rhs: Self) -> Bool Required

Returns a Boolean value indicating whether the value of the first argument is less than or equal to that of the second argument.

This is the default implementation of the less-than-or-equal-to operator (<=) for any type that conforms to Comparable.

Declaration

@inlinable public static func <=(lhs: Self, rhs: Self) -> Bool
func ==(lhs: Character, rhs: Character) -> Bool Required

Returns a Boolean value indicating whether two values are equal.

Equality is the inverse of inequality. For any values a and b, a == b implies that a != b is false.

Declaration

@inlinable public static func ==(lhs: Character, rhs: Character) -> Bool
func >(lhs: Self, rhs: Self) -> Bool Required

Returns a Boolean value indicating whether the value of the first argument is greater than that of the second argument.

This is the default implementation of the greater-than operator (>) for any type that conforms to Comparable.

Declaration

@inlinable public static func >(lhs: Self, rhs: Self) -> Bool
func >=(lhs: Self, rhs: Self) -> Bool Required

Returns a Boolean value indicating whether the value of the first argument is greater than or equal to that of the second argument.

This is the default implementation of the greater-than-or-equal-to operator (>=) for any type that conforms to Comparable.

Declaration

@inlinable public static func >=(lhs: Self, rhs: Self) -> Bool