Swift Character

Swift's character is a single character string literally, with a data type of 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 execution is:

char1 的值为 A
char2 的值为 B

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

import Cocoa

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

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

The output of the above program execution is:

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

The empty character variable

You cannot create an empty Character type variable or constant in Swift:

import Cocoa

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

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

The output of the above program execution 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 = ""

Traverse the characters in the string

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

You can get the value of each character by traversing the acters property in the string through the for-in loop:

import Cocoa

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

The output of the above program execution is:

H
e
l
l
o

String connection characters

The following example demonstrates using String's append() method to implement string connection characters:

import Cocoa

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

varA.append( varB )

print("varC  =  \(varA)")

The output of the above program execution is:

varC  =  Hello G