Rob
Rob

Reputation: 15992

How to get a character from its ASCII value?

I want to get letters from their ASCII code in Swift 3. I would do it like this in Java :

for(int i = 65 ; i < 75 ; i++)
{
    System.out.print((char)i);
}

Which would log letters from A to J.

Now I tried this in Swift :

let s = String(describing: UnicodeScalar(i))

Instead of only getting the letter, I get this :

Optional("A")
Optional("B")
Optional("C")
...

What am I doing wrong? Thanks for your help.

Upvotes: 1

Views: 761

Answers (1)

Hamish
Hamish

Reputation: 80781

UnicodeScalar has a few failable initialisers for integer types that can reprent values that aren't valid Unicode code points. Therefore you'll need to unwrap the UnicodeScalar? returned, as in the case that you pass an invalid code point, the initialiser will return nil.

However, given that you're dealing exclusively with ASCII characters, you can simply annotate i as a UInt8 and take advantage of the fact that UnicodeScalar has a non-failable initialiser for a UInt8 input (as it will always represent a valid code point):

for i : UInt8 in 65..<75 {
    print(UnicodeScalar(i))
}

Upvotes: 7

Related Questions