Rahul gupta
Rahul gupta

Reputation: 129

How to print Unicode Characters in Swift

I want to print Unicode characters for some special symbol like `,',@,$ so please let me know if there is any method which converts string to unicode characters like \u00e2...

Thanks,

Upvotes: 0

Views: 1583

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236260

You can get your string unicodeScalars value, convert to hexa and finish padding it with leading zeros:

extension String {
    var unicodes: [String] {
        return unicodeScalars.map{ String($0.value, radix: 16) }
    }
    func paddingToLeft(maxLength: Int) -> String {
        return repeatElement("0", count: max(0,maxLength-count)) + self
    }
}

let str =  "\u{00e2}"
let hexa = str.unicodes.first!
print(hexa.paddingToLeft(maxLength: 4))  // "00e2\n"

Upvotes: 1

Related Questions