How to convert an ASCII value to a character in Swift
Overview
In Swift, every numerical ASCII value has its corresponding and equivalent character value. To convert an ASCII value to its equivalent character, we use the UnicodeScalar() function.
Syntax
UnicodeScalar(asciiValue)
Parameters
asciiValue: This is the ASCII value we want to convert to a character.
Return value
This method returns a character that is the corresponding equivalent of the specified ASCII value.
Example
import Swift;// Create some ASCII valuesvar asciiVal1 = 968;var asciiVal2 = 402;var asciiVal3 = 65;var asciiVal4 = 85;// Convert the ASCII values to a charactersvar char1 = UnicodeScalar(asciiVal1)!var char2 = UnicodeScalar(asciiVal2)!var char3 = UnicodeScalar(asciiVal3)!var char4 = UnicodeScalar(asciiVal4)!// Print the converted charactersprint("Char: ",char1);print("Char: ",char2);print("Char: ",char3);print("Char: ",char4);
Explanation
- Lines 4–7: We create some ASCII values.
- Lines 10–13: We convert these ASCII values to characters using the
UnicodeScalar()method. - Lines 16–19: We print the characters to the console.