lusher00 lusher00 - 14 days ago 5x
Swift Question

converting string to data in swift 3.0

I'm trying to convert a string to a data type. I thought this was all I needed but if I try to print it it just prints "12 bytes"

let tString = "Hello World!"
if let newData = String.Encoding.utf8){
self.peripheral?.writeValue(newData, for: positionCharacteristic, type: CBCharacteristicWriteType.withResponse)

What am I doing wrong?


You are not doing anything wrong. That's just how Data currently does its debug printout. It has changed over time. It has at times printed more like NSData. Depending on the debug print format is pretty fragile, I think it's better to just own it more directly. I have found the following pretty useful:

extension Data {
    func hex(separator:String = "") -> String {
        return ( { String(format: "%02X", $0) }).joined(separator: separator)

This allows me to replace your simple print(newData) with something like




if my eyes need help parsing the bytes

aside, I do quite a bit of BLE stuff myself, and have worked up a number of other useful Data extensions for BLE stuff