johni
johni

Reputation: 5568

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.

Upvotes: 2

Views: 6701

Answers (2)

vacawama
vacawama

Reputation: 154583

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"

Upvotes: 10

Abhi Beckert
Abhi Beckert

Reputation: 33359

If what you're looking for is as string rather than a character (seems more useful for what you're trying to do? You said you have bytes, but asked about individual characters)?

Anyway you can do this with NSString:

var char = 97

let str = NSString(bytes: &char, length: 1, encoding: NSUTF8StringEncoding)

You said you're using NSInputStream... here's how to put that together:

// create a stream to work with
let data = NSData(contentsOfURL: NSURL(string: "http://abhibeckert.com/"))
let stream = NSInputStream.inputStreamWithData(data)

// read from the stream
var buffer = [UInt8](count:100, repeatedValue: 0)
stream.open()

while stream.hasBytesAvailable {
  stream.read(&buffer, maxLength: buffer.count)

  // get a string for the current section of the buffer
  let str = NSString(bytes: buffer, length: buffer.count, encoding: NSUTF8StringEncoding)
}

Upvotes: 1

Related Questions