Reputation: 1480
I need to convert my Byte
to a String
because
- (NSInteger)write:(const uint8_t *)buffer maxLength:(NSUInteger)
takes a String
as its first parameter.
What I want:
func sendMessage(message: Byte) -> Int {
return outputStream!.write(message, maxLength: 1)
}
Upvotes: 2
Views: 4653
Reputation: 1112
For others who came here for the answer to the question:
"How do I convert an Array
of bytes into a Swift String
" :
String(bytes: byteArray, encoding: NSUTF8StringEncoding)
which returns a String?
(Optional<String>
).
Upvotes: 0
Reputation: 1285
You can convert a UnicodeScalar
to a String
as such:
let theString = String(UnicodeScalar(theByte))
Or you can do it one Character
at a time:
let theChar = Character(UnicodeScalar(theByte))
Upvotes: 0
Reputation: 3258
The documentation for NSOutputStream
actually shows what @Kirsteins suggested, when looking at the Swift version of the method:
func write(_ buffer: UnsafePointer<UInt8>, maxLength length: Int) -> Int
Upvotes: 0
Reputation: 27335
You don't have to provide string, but UnsafePointer<UInt8>
. Just prepend message
with &
:
return outputStream!.write(&message, maxLength: 1)
Upvotes: 3
Reputation: 617
Try this
var char = 97
let str = NSString(bytes: &char, length: 1, encoding: NSUTF8StringEncoding)
Upvotes: 0