Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Characters (Character)

Swift Characters

A character (Character) represents one character as seen by the human eye and is the building block of a string.

Swift's Character is neither a byte nor a Unicode code point, but an extended grapheme cluster — the biggest difference from char in C-family languages.

This article covers the meaning of Character, extended grapheme cluster semantics, conversion to and from String, and the difference between literals and type annotations; for the use of strings themselves, see "Swift Strings》。


What is a Character?

Character represents a single extended grapheme cluster; it must be assigned with double quotes and can hold only one character.

The declaration must include a type annotation, otherwise the compiler infers the content inside the quotes as String rather than Character.

Example

let char1

:

Character

=

"A"

let char2

:

Character

=

"A"

print

(

"char1's value is (char1)"

)

print

(

"char2's value is (char2)"

)

Running result:



char1 的值为 A

char2 的值为 牛

Note:Character It cannot be an empty string, nor can it hold multiple characters. Writing let c: Character = "AB" or let c: Character = "" will raise cannot convert value of type 'String' to specified type 'Character'。

A string consists of several Characters; when iterating with for-in, each element produced is a Character.

Example

for

ch in

"Runoob"

{

    print

(

ch

)

}

Running result:



R

u

n

o

o

b

Each ch printed here is a Character, not a String, so it can directly take part in Character operations and comparisons.


Extended grapheme cluster semantics

In Swift, "one character" refers to oneextended grapheme cluster(extended grapheme cluster), that is, one character as seen by the human eye, rather than the underlying bytes or code units.

Letters with diacritics, emoji with skin-tone modifiers, and family symbols composed of several emoji all count as one Character.

Example

// The precomposed é is one character

let precomposed

=

"\u{00E9}"

// e plus a combining accent is also "one" character, because it is the same extended grapheme cluster

let combined

=

"e\u{0301}"

print

(

"precomposed count: (precomposed.count)"

)

print

(

"combined count: (combined.count)"

)

print

(

"The two are equal: (precomposed == combined)"

)

// A family emoji made of four members also counts as one character

let family

=

"👨‍👩‍👧‍👦"

print

(

"family count: (family.count)"

)

// Emoji with a skin-tone modifier

let thumbsUp

=

"👍🏽"

print

(

"thumbsUp count: (thumbsUp.count)"

)

Running result:



precomposed 的 count:1

combined 的 count:1

两者相等:true

family 的 count:1

thumbsUp 的 count:1

These examples have in common that the number of underlying Unicode scalars is more than one, but they all belong to the same extended grapheme cluster, so count is 1 in each case.

The boundary rules for extended grapheme clusters are defined by the Unicode standard, which Swift adopts directly; therefore intuitions about "one character" from different languages mostly line up in Swift.


Converting between Character and String

Character and String can be converted into each other; the most common forms are listed below.

Direction Syntax Description
String to a character array Array(str) Get a [Character]
String to a single character for c in str c in each iteration is a Character
Character to String String(c) Get a single-character string
Character array to String String(chars) Join [Character] back into a string
Append a Character to a string str.append(c) str must be a var

Example

let str

=

"Runoob"

// Use Array to split a string into a character array

let chars

=

Array

(

str

)

print

(

chars

)

print

(

chars.

count

)

// Take out a character, then convert it back to a string

let first

:

Character

=

chars

[

0

]

let asString

=

String

(

first

)

print

(

asString

)

print

(

type

(

of

:

asString

)

)

Running result:



["R", "u", "n", "o", "o", "b"]

6

R

String

Conversely, a Character can be appended to the end of a string with append.

Example

var text

=

"Hello "

let exclamation

:

Character

=

"!"

text.

append

(

exclamation

)

print

(

text

)

Running result:



Hello !

To join a character array back into a string, write String(chars) directly; if you want a separator, first convert each Character to String and then use joined(separator:), because [Character] has no such method of its own.

Example

let str

=

"Runoob"

let chars

=

Array

(

str

)

// Join a character array back into a string

print

(

String

(

chars

)

)

print

(

chars.

map

(

String.

init

)

.

joined

(

separator

:

"-"

)

)

Running result:



Runoob

R-u-n-o-o-b


Character literals and type annotations

The content inside double quotes defaults to String, even if it is a single character; only an explicit type annotation or a conversion with as Character yields a Character.

Example

let inferred

=

"C"

let

explicit

:

Character

=

"C"

let casted

=

"C"

as Character

print

(

type

(

of

:

inferred

)

)

print

(

type

(

of

:

explicit

)

)

print

(

type

(

of

:

casted

)

)

Running result:



String

Character

Character

The three lines look the same but have different types: inferred is a String, the other two are Characters. When you need a Character, prefer a type annotation, which is more intuitive than an as conversion.

The same applies when converting from a variable: Character(someString) can convert a String whose content is exactly one character into a Character, but if the string is empty or longer than one character, the program terminates at runtime, so verify the content before converting.


Common questions

Here are the questions beginners most often encounter when using Character.

Why is "👨‍👩‍👧‍👦".count equal to 1?

This family emoji consists of four member emoji and three zero-width joiners; at the lower level it has 7 Unicode scalars and 25 UTF-8 bytes, but they belong to the same extended grapheme cluster and appear to the eye as a single symbol, so count is 1.

Can a Character be compared directly with a String?

No. There is no == overload between Character and String, so c == s (where s is a String variable) reports binary operator '==' cannot be applied to operands of type 'Character' and 'String'. But c == "A" is valid because the literal "A" is inferred as a Character; to compare with a String variable, convert first with String(c).

Example

let c

:

Character

=

"A"

let s

=

"A"

// The literal is inferred as a Character and can be compared directly

print

(

"c == "A":(c == "

A

")"

)

// c == s does not compile; there is no == overload between Character and String

print

(

"String(c) == s:(String(c) == s)"

)

print

(

"c == Character(s):(c == Character(s))"

)

Running result:



c == "A":true

String(c) == s:true

c == Character(s):true

How to split a string into a character array

Use Array(str) to get a [Character], after which all collection operations — array subscripts, map, filter, and so on — are available; if you only want to iterate without storing, for c in str is simpler.

Can a Character hold an empty string?

No. Both an empty string and a multi-character string report cannot convert value of type 'String' to specified type 'Character'. To represent "no character", use the optional type Character? and assign nil.