Somendra Yadav
2 min readAug 21, 2020

--

While Localising an application, I hit a road block, this api was using ASCII code for language conversion.

String with some prefix and suffix. That’s why I convert Japanese language character on ASCII then send it to server.

This is small tutorial to convert Language Character to exact unicode and unicode to ASCII and Unicode to language.

Every time this unicodeScalars will return a String but we can iterate this string and convert into unicode with the help of this method $0.escaped(asASCII: true)

In this method A Boolean value indicating whether the Unicode scalar is an ASCII character.

ASCII characters have a scalar value between 0 and 127, inclusive. For

example:


let
language = “エアテル”
var strJap = “”let cs = CharacterSet(charactersIn: “\\u{}”)language.unicodeScalars.forEach{strJap.append(“prefixValue” + $0.escaped(asASCII: true).trimmingCharacters(in: cs) + “suffixValue”)}print(strJap)//prefixValue30a2suffixValue

if you want convert unicode to character so you can use this :

var str: String = "I want to visit 北京, Москва, मुंबई, القاهرة, and 서울시. 😊"
var character: Character = "🌍"

Use hexadecimal to set values

var str: String = "\u{61}\u{5927}\u{1F34E}\u{3C0}" // a大🍎π
var character: Character = "\u{65}\u{301}" // é = "e" + accent mark

Note that the Swift Character can be composed of multiple Unicode code points, but appears to be a single character. This is called an Extended Grapheme Cluster.

Convert to Unicode values:

str.utf8
str.utf16
str.unicodeScalars // UTF-32

String(character).utf8
String(character).utf16
String(character).unicodeScalars

Convert from Unicode hex values:

let hexValue: UInt32 = 0x1F34E
if let scalarValue = UnicodeScalar(hexValue) {
let myString = String(scalarValue)// 🍎
}

A few more examples

let value0: UInt8 = 0x61
let value1: UInt16 = 0x5927
let value2: UInt32 = 0x1F34E
let string0 = String(UnicodeScalar(value0)) // a
let string1 = String(UnicodeScalar(value1)) // 大
let string2 = String(UnicodeScalar(value2)) // 🍎
// convert hex array to String
let myHexArray = [0x43, 0x61, 0x74, 0x203C, 0x1F431] // an Int array
var myString = ""
for hexValue in myHexArray {
myString.append(UnicodeScalar(hexValue))
}
print(myString) // Cat‼🐱

Some times we get in trouble, why some kind of unicode is not Convertible into emoji, because they are not supported in iOS or we don’t get the proper unicode.So you can check by this links:

Unicode standard emoji’s(which is supported in iOS): https://unicode.org/Public/emoji/12.1/

There are lot of unicode emoji’s which is supported in android: https://gist.github.com/dgmltn/69e450921ecb64b0df5fc4d8414fd830

Thanks for reading. If you love this post, save or share it to friends.

Feel free to clap 👏👏 if you like this story.

--

--

Somendra Yadav

Senior iOS Engineer with 5 year of experience in creating efficient and scalable mobile apps. Always eager to learn and create great things.