Doug Null
Doug Null

Reputation: 8327

Why does Swift unexpectedly insert “Optional” at the beginning of stringFromData?

I run this code on an iPad to create virtual BLE peripheral.
It starts advertising.
I run the central on iPhone.
Central detects peripheral and connects and subscribes.
Peripheral log unexpectedly has "Optional" in the log, though it's not in stringFromData.

IMAGE SHOWS stringFromData CONTENT AND LOG.........

enter image description here

class PeripheralViewController: UIViewController {
    var packet_to_send = Data()

. . .


    func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
        os_log("Central subscribed to characteristic")
        
        // Init 1st sim packet:
        packet_to_send = ("antenna data chunk " + String( packet_number )).data(using: .utf8)!         
            let stringFromData = String(data: packet_to_send, encoding: .utf8)
            os_log("initial packet_to_send %d bytes = '%s'.", packet_to_send.count, String( describing: stringFromData))

Upvotes: 0

Views: 28

Answers (1)

David Pasztor
David Pasztor

Reputation: 54805

stringFromData is an Optional. When you use String(describing:) to get the description of an Optional, it will be "Optional(yourDescription)" rather than "yourDescription".

You can avoid this by converting the Optional<String> into a String using optional binding or by providing a default value.

let stringFromData = String(data: packet_to_send, encoding: .utf8) ?? ""
os_log("initial packet_to_send %d bytes = '%s'.", packet_to_send.count, stringFromData)

Upvotes: 2

Related Questions