Swift characters
Swift's character is a single character string literal with the data type 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 execution output of the above program is:
char1 的值为 A char2 的值为 B
If you want to store it in a constant of type Character If there are more characters, the program execution will report an error, as shown below:
import Cocoa // Swift 中以下赋值会报错 let char: Character = "AB" print("Value of char \(char)")
The output result of the above program execution is:
error: cannot convert value of type 'String' to specified type 'Character' let char: Character = "AB"
Empty character variable
Swift Medium An empty Character (character) cannot be created. Type variable or constant:
import Cocoa // Swift 中以下赋值会报错 let char1: Character = "" var char2: Character = "" print("char1 的值为 \(char1)") print("char2 的值为 \(char2)")
The above program execution output result 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 The String type represents a specific sequence of a collection of Character type values. Each character value represents a Unicode character.
You can use a for-in loop to traverse the characters attribute in the string to obtain the value of each character:
import Cocoa for ch in "Hello".characters { print(ch) }
The output result of the above program execution is:
H e l l o
String connection characters
The following example demonstrates the use of 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 execution output of the above program is:
varC = Hello G