Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of unicode values of currency symbols in Swift?

Tags:

ios

swift

unicode

Unicode values are:
U+20A0 to U+20AF

All these values represent currency symbol. Check the following link for reference: https://en.wikipedia.org/wiki/Currency_Symbols_(Unicode_block)

In swift, I can print the currency symbol associated with a unicode with the following code:

let rupee = "\u{20B9}"    //Its currency symbol "₹"

My goel is to show all currency symbols in a table and for this purpose, I want to create an array of unicode values whose range I have mentioned above. I have used the following code to create an array, but there is problem in the step in which I am creating the unicode :

var unicodeArray:[String] = [String]()
for var decNumber=0; decNumber < 16; decNumber++ {
    let hexVal = String(decNumber, radix: 16)
    let unicode = "{20A\(hexVal)}"  \\u is missing in the string, writing \u gives error"
    unicodeArray.append(unicode)
}

After the for loop, array would have values between {20A0} to {20AF}, But I need the values from "\u{20A0}" to "\u{20AF}". How can I fix this. Or Is there any other way of doing what I am trying?

like image 294
Deep Arora Avatar asked Dec 01 '25 20:12

Deep Arora


1 Answers

Edited: Used swift style loop as per suggestion @Grimxn

Try this:

var unicodeArray:[String] = [String]()
for decNumber in 0..<16 {
    let hexVal = String(decNumber, radix: 16)
    let integer = Int(strtoul("20A\(hexVal)", nil, 16))
    let unicode = UnicodeScalar(integer)

    unicodeArray.append(String(unicode))
}

Basically it prepares the hex values as Int. Then UnicodeScalar converts them to unicode. Which you can then convert into a String.

like image 109
John Bennedict Lorenzo Avatar answered Dec 04 '25 12:12

John Bennedict Lorenzo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!