Swift - Characters



A character in Swift is a single character String literal such as “A", "!", “c", addressed by the data type Character. Or we can say that the character data type is designed to represent a single Unicode character.

Syntax

Following is the syntax to declare a character data type −

var char : Character = "A" 

Example

Swift program to create two variables to store characters.

import Foundation

let char1: Character = "A"
let char2: Character = "B"

print("Value of char1 \(char1)")
print("Value of char2 \(char2)")

Output

Value of char1 A
Value of char2 B

Example

If we try to store more than one character in a Character type variable or constant, then Swift will not allow that and give an error before compilation.

import Foundation

// Following is illegal in Swift 
let char: Character = "AB"

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

Output

main.swift:4:23: error: cannot convert value of type 'String' to specified type 'Character'
let char: Character = "AB"

Example

Also, we are not allowed to create an empty Character variable or constant which will have an empty value. If we try to do we will get an error.

import Foundation

// Creating empty Character
let char1: Character = ""
var char2: Character = ""

print("Value of char1 \(char1)")
print("Value of char2 \(char2)")

Output

main.swift:4:24: error: cannot convert value of type 'String' to specified type 'Character'
let char1: Character = ""
                       ^~
main.swift:5:24: error: cannot convert value of type 'String' to specified type 'Character'
var char2: Character = ""
                       ^~

Accessing Characters from Strings in Swift

A string represents a collection of Character values in a specified order. So we can access individual characters from the given String by iterating over that string with a for-in loop −

Example

import Foundation

// Accessing Characters from Strings using for-in loop
for ch in "Hello" {
   print(ch)
}

Output

H
e
l
l
o

Concatenating String with Character in Swift

In Swift, we can concatenate String with a character using the + and += operators. Both the operators concatenate the given character at the end of the specified string.

While concatenating a string with a character we required an explicit conversion from character to string because Swift enforces strong typing. Also, we are not allowed to concatenate a character(variable) with a string.

Example

Swift program to concatenate a string with a character using the + operator.

import Foundation

let str = "Swift"
let char: Character = "#"

// Concatenating string with character using + operator
let concatenatedStr = str + String(char)

print(concatenatedStr)

Output

Swift#

Example

Swift program to concatenate a string with a character using the += operator.

import Foundation

var str = "Swift"
let char: Character = "!"

// Concatenating string with character using += operator
str += String(char)
print(str)

Output

Swift!
Advertisements