Swift无法将NSDictionaryM的值强制转换为NSData

时间:2019-03-13 08:43:50

标签: swift nsdictionary

Output:    
({
    "Client Characteristic Configuration" = <41424344 45463132 31323334 35363738 45324441>;
})

Code : 
print("localName4", localName4)

if (localName4 != nil) {
    print("exists")

    if localName4 is Dictionary<AnyHashable,Any> {
        print("Yes, it's a Dictionary")

        do {
            if let jsonResult = try JSONSerialization.jsonObject(with: localName4 as! Data, options: []) as? NSDictionary {
                print(jsonResult)
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
}

我正在尝试从结果中获取值<41424344 45463132 31323334 35363738 45324441>。当我尝试解析获取异常的值时:

  

无法将类型“ NSDictionaryM”的值强制转换为“ NSData”

1 个答案:

答案 0 :(得分:0)

无需将其强制转换为Data并将其序列化回Dictionary。要访问字典中的值,只需按以下键即可调用它们:

let configuration = localName4["Client Characteristic Configuration"]

如果localName4的声明类型不是[AnyHashable : Any],请尽可能更改声明或将其强制转换为这样:

if let dict = localName4 as? [AnyHashable : Any] {
    let configuration = dict["Client Characteristic Configuration"]
    ...
}