Swift Character, Operations on Character
In Swift, Character
is a value type that represents a single extended grapheme cluster, which is a sequence of one or more Unicode scalars that combine to produce a single human-readable character. Operations on Character
can be useful when working with user inputs, data processing, or data validation.
Creating a Character
A Character
can be created from a single character literal, which is a single character enclosed in single quotes:
1let exclamationMark: Character = "!"
It can also be created from a string by using the first
property of the string, which returns the first character:
1let hello = "hello" 2let firstCharacter = hello.first // returns Optional("h")
Note that the first
property returns an optional value since the string may be empty.
String Interpolation with Character
Character
values can be interpolated into strings by using the \()
syntax:
1let letter: Character = "a" 2let message = "The first letter of the alphabet is \(letter)."
Operations on Character
Counting Characters
The count
property of a String
returns the number of characters in the string. Since Character
represents a single character, the count
property of a Character
always returns 1
:
1let exclamationMark: Character = "!" 2let count = exclamationMark.count // returns 1
Checking for Equality
You can use the ==
operator to check if two Character
values are equal:
1let a: Character = "a" 2let b: Character = "b" 3if a == b { 4 print("a and b are the same character.") 5} else { 6 print("a and b are different characters.") 7}
Converting to a String
A Character
can be converted to a String
by using the String
initializer:
1let exclamationMark: Character = "!" 2let string = String(exclamationMark)
Checking for Digit
You can check if a Character
represents a digit using the isDigit
property:
1let digit: Character = "5" 2let nonDigit: Character = "a" 3if digit.isDigit { 4 print("\(digit) is a digit.") 5} 6if !nonDigit.isDigit { 7 print("\(nonDigit) is not a digit.") 8}
Checking for Letter
You can check if a Character
represents a letter using the isLetter
property:
1let letter: Character = "a" 2let nonLetter: Character = "5" 3if letter.isLetter { 4 print("\(letter) is a letter.") 5} 6if !nonLetter.isLetter { 7 print("\(nonLetter) is not a letter.") 8}
Checking for Whitespace
You can check if a Character
represents whitespace using the isWhitespace
property:
1let whitespace: Character = " " 2let nonWhitespace: Character = "a" 3if whitespace.isWhitespace { 4 print("\(whitespace) is whitespace.") 5} 6if !nonWhitespace.isWhitespace { 7 print("\(nonWhitespace) is not whitespace.") 8}