Swift Character
A character in Swift 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 is \(char1)")
print("char2 is \(char2)")
The output of the above program is:
char1 is A
char2 is B
If you try to store more characters in a constant of type Character, the program will throw an error, as shown below:
import Cocoa
// The following assignment will cause an error in 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 variable or constant:
import Cocoa
// The following assignment will cause an error in Swift
let char1: Character = ""
var char2: Character = ""
print("char1 is \(char1)")
print("char2 is \(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
The String type in Swift represents a sequence of Character values. Each character value represents a Unicode character.
In Swift 4, attributes and methods that were accessed through characters
in Swift 3 can now be directly called on the String object, for example:
In Swift 3:
import Cocoa
for ch in "tutorialpro".characters {
print(ch)
}
In Swift 4:
import Cocoa
for ch in "tutorialpro" {
print(ch)
}
The output of the above program is:
R
u
n
o
o
b
Concatenating Characters to a String
The following example demonstrates how to concatenate characters to a string using the append()
method of 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