Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
character
ascii
communitycreator

How to convert an ASCII value to a character in Swift

Theodore Kelechukwu Onyejiaku

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);
Converting ASCII values to their corresponding characters

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.

RELATED TAGS

swift
character
ascii
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring