johni johni - 4 months ago 33
Swift Question

Convert a byte to char in Swift

I'm using NSInputStream to read msgs.
The read method returns the msg in bytes, same like in Java.
I would like to take the byte and print it as char (e.g. in Java

println((char) 97) // prints "a"
)

How would I do that in Swift?

Thank you.

Answer

This works:

let b: UInt8 = 97

print(Character(UnicodeScalar(b)))

If you wanted to make this cleaner, you could extend UInt8 and Int:

extension UInt8 {
    var char: Character {
        return Character(UnicodeScalar(self))
    }
}

extension Int {
    var char: Character {
        return Character(UnicodeScalar(self))
    }
}

print(b.char)   // prints "a"
print(98.char)  // prints "b"