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 values
var asciiVal1 = 968;
var asciiVal2 = 402;
var asciiVal3 = 65;
var asciiVal4 = 85;
// Convert the ASCII values to a characters
var char1 = UnicodeScalar(asciiVal1)!
var char2 = UnicodeScalar(asciiVal2)!
var char3 = UnicodeScalar(asciiVal3)!
var char4 = UnicodeScalar(asciiVal4)!
// Print the converted characters
print("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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources