我正在读取一个 usb-rawHID-device
var read_byteArray = [UInt8](repeating: 0x00, count: BUFFER_SIZE)
var result = rawhid_recv(0, &read_byteArray, Int32(BUFFER_SIZE), 50)
我可以读取 read_byteArray
for i in 0...16
{
print(" \(read_byteArray[i])", terminator: "")
}
+++ new read_byteArray in Timer: 0 9 69 0 0,...
然后我想通过通知来分发数据。
let nc = NotificationCenter.default
nc.post(name:Notification.Name(rawValue:"newdata"),
object: nil,
userInfo: ["data":read_byteArray])
我注册通知并阅读它
@objc func newDataAktion(_ notification:Notification)
{
print("new Data")
let data = notification.userInfo?["data"]
print("data: \(String(describing: data)) \n") // data: Optional([0, 9, 51, 0,....
if let d = notification.userInfo!["data"]
{
print("d: \(d)\n") // d: [0, 9, 56, 0, 0,...
let t = type(of:d)
print("typ: \(t)\n") // typ: Array<UInt8>
}
}
数据是数组类型,但我尝试使用读取该数组的元素
print("element: \(d[1])\n")
给我错误
Type 'Any' has no subscript members
如何从数据中获取 UInt8 元素?
最佳答案
用户信息字典的类型为[String: Any]
,因此当您从 if 中获取 key 时,您还应该将其转换为正确的类型(否则它包含在 Any
并且它不是一个数组;type(of:)
可以在运行时告诉您它是一个 [UInt8]
,但编译器在编译时无法知道这一点除非你告诉它):
if let d = notification.userInfo?["data"] as? [UInt8] {
d.forEach{ print($0) }
}
关于swift - 来自 notification.userInfo 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53506103/