Swift character (Character)
Swift's character is a single character string literal, the data type of Character.
The following example shows the two characters Example:
import Cocoa
let char1: Character = "A"
let char2: Character = "B"
print("char1 的值为 \(char1)")
print("char2 的值为 \(char2)")
The above program execution output is:
char1 的值为 A char2 的值为 B
If you want to Character (character) type constants stored in more characters, the program execution will be given as follows:
import Cocoa
// Swift 中以下赋值会报错
let char: Character = "AB"
print("Value of char \(char)")
The above program execution output is:
error: cannot convert value of type 'String' to specified type 'Character' let char: Character = "AB"
Null character variable
Swift can not create an empty Character (character) type variable or constant:
import Cocoa
// Swift 中以下赋值会报错
let char1: Character = ""
var char2: Character = ""
print("char1 的值为 \(char1)")
print("char2 的值为 \(char2)")
The above program execution output 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 = ""
Traversal characters in a string
Swift represents a collection of type String Character specific sequence (character) type values. Each character represents a Unicode character.
You can string of characters to traverse the attributes for-in loop to get the value of each character:
import Cocoa
for ch in "Hello".characters {
print(ch)
}
The above program execution output is:
H e l l o
Character string concatenation
String The following example demonstrates the use of the append () method to achieve the connection string of characters:
import Cocoa
var varA:String = "Hello "
let varB:Character = "G"
varA.append( varB )
print("varC = \(varA)")
The above program execution output is:
varC = Hello G