Swift Character

Swift's Character is a single-character string literal, and its data type is Character.

The following example lists two Character instances:

import Cocoa

let char1: Character = "A"
let char2: Character = "B"

print("char1 的值为 \(char1)")
print("char2 的值为 \(char2)")

The output of the above program is:

char1 的值为 A
char2 的值为 B

If you want to store more characters in a constant of type Character, the program will report an error, as shown below:

import Cocoa

// Swift 中以下赋值会报错
let char: Character = "AB"

print("Value of char \(char)")

The output of the above program is:

error: cannot convert value of type 'String' to specified type 'Character'
let char: Character = "AB"

Empty Character Variable

In Swift, you cannot create an empty Character type variable or constant:

import Cocoa

// Swift 中以下赋值会报错
let char1: Character = ""
var char2: Character = ""

print("char1 的值为 \(char1)")
print("char2 的值为 \(char2)")

The output of the above program is:

 error: cannot convert value of type 'String' to specified type 'Character'
let char1: Character = ""
                       ^~
error: cannot convert value of type 'String' to specified type 'Character'
var char2: Character = ""

Iterating over Characters in a String

Swift's String type represents a collection of Character type values in a specific sequence. Each character value represents a Unicode character.

In Swift 3, the properties and methods of String need to be called through characters. In Swift 4, they can be called directly through the String object itself, for example:

In Swift 3:

import Cocoa

for ch in "Example".characters {
    print(ch)
}

In Swift 4:

import Cocoa

for ch in "Example" {
    print(ch)
}

The output of the above program is:

R
u
n
o
o
b

Concatenating Characters to a String

The following example demonstrates using the append() method of String to concatenate a character to a string:

import Cocoa

var varA:String = "Hello "
let varB:Character = "G"

varA.append( varB )

print("varC  =  \(varA)")

The output of the above program is:

varC  =  Hello G
Other Extensions