首页 > 解决方案 > Can 8 bytes be NIL?

问题描述

I am trying to build a BLE packet that contains a RGB color and !C to ID the packet type, using the built-in color picker and some math it works well to get the RGB values and converting the Int to Data seems to work fine but it throws a Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

var s1 = lroundf(Float(Character("!").asciiValue!))
var s2 = lroundf(Float(Character("C").asciiValue!))

var rint = lroundf(Float(r*255))
var gint = lroundf(Float(g*255))
var bint = lroundf(Float(b*255))
let s1data = Data(bytes: &s1, count: MemoryLayout.size(ofValue: s1))
let s2data = Data(bytes: &s2, count: MemoryLayout.size(ofValue: s2))
let rdata = Data(bytes: &rint, count: MemoryLayout.size(ofValue: rint))
let gdata = Data(bytes: &gint, count: MemoryLayout.size(ofValue: gint))
let bdata = Data(bytes: &bint, count: MemoryLayout.size(ofValue: bint))
print("The data going into this packet is, s1: \(s1data), s2: \(s2data), rdata: \(rdata), gdata: \(gdata), bdata: \(bdata)")
packet.append(s1data)
packet.append(s2data)
packet.append(rdata)
packet.append(gdata)
packet.append(bdata)

return packet

The output from this segment is:

The data going into this packet is, s1: 8 bytes, s2: 8 bytes, rdata: 8 bytes, gdata: 8 bytes, bdata: 8 bytes
DQ_Plate/ViewController.swift:87: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
2021-11-09 13:33:03.509765-0600 DQ Plate[567:20901] DQ_Plate/ViewController.swift:87: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value 

It fails on the line with packet.append(s1data) but as you can see from the output it has 8 bytes

Not sure what is happening here…</p>

标签: iosswift3core-bluetooth

解决方案


推荐阅读