Kilian Koeltzsch Kilian Koeltzsch - 1 year ago 426
Swift Question

Converting to Char/String from Ascii Int in Swift

I'm trying to convert the integer representation of an ascii character back into a string.

string += (char) int;

In other languages like Java (the example here) I can just cast the integer into a char. Swift obviously does not know these and I'm guessing using the all powerful NSString somehow will be able to do the trick.

Answer Source

It may not be as clean as Java, but you can do it like this:

var string = ""

You can also modify the syntax to look more similar if you like:

//extend Character so it can created from an int literal
extension Character: IntegerLiteralConvertible {
    public static func convertFromIntegerLiteral(value: IntegerLiteralType) -> Character {
        return Character(UnicodeScalar(value))

//append a character to string with += operator
func += (inout left: String, right: Character) {

var string = ""
string += (50 as Character)

Or using dasblinkenlight's method:

func += (inout left: String, right: Int) {
    left += "\(UnicodeScalar(right))"
var string = ""
string += 50
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download