How to add binary to a string in Swift?

Does anyone know how to add binary code to a string in swift?


I'd like to convert from ObjC to Swift someing like this


#define PRINTER_CMD_SMALLTEXT @"\x1b\x21\x01\x1b\x33\x0a"


to this...


let PRINTER_CMD_SMALLTEXT: String = "\x1b\x21\x01\x1b\x33\x0a"


but \x is not accepted

Guess: code the string as unicode scalers


let PRINTER_CMD_SMALLTEXT: String = "\u{1b}\u{21}\u{01}\u{1b}\u{33}\u{0a}"

As marchyman says, you can do this with Unicode escaping. However, you might be better off using an array of UInt8.

let PRINTER_CMD_SMALLTEXT: [UInt8] = [ 0x1b, 0x21, 0x01, 0x1b, 0x33, 0x0a ]

Swift strings are all Unicode based, which is good when dealing with user-facing text but less than ideal when dealing with on-the-wire networking protocols.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Thanks Quinn - this works great when pushing data directly (and for debugging bytes), but since I'm appending to other strings, marchyman's makes it easier to use A + B

Works great. Thanks!

… since I'm appending to other strings, marchyman's makes it easier to use A + B

Which is fine as long as you don’t use any characters out of the range 0…127. Once you start doing that you’ll have to worry about text encodings, at which point an array of

UInt8
(or an NSData) starts making more sense.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
How to add binary to a string in Swift?
 
 
Q