swift - 来自 notification.userInfo 的数据

标签 swift notifications any uint8t

我正在读取一个 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/

相关文章:

等效于 LINQ Any() 的 JavaScript/jQuery

json - jq:当数组中有任何值时选择

ios - Swift 3 到 4 - '#selector' 的参数引用未公开给 Objective-C 的实例方法 'handleScreenTap(sender:)'

macos - 如何从 OSX Yosemite 的命令行触发通知?

Android 推送通知(慢)

Android:如何从通知中恢复 fragment 类。不创建新实例

python - any() 与字符串序列

Xcode Beta 6 - 使用未声明的类型 'CLLocationManagerDelegate'

ios - 使用 SwiftyJSON 和 Alamofire 在 TableView 上获取 JSON 数据

swift - 在 swift 应用程序开发中使用未声明的类型