问题描述
我正在尝试在新项目上使用OpenKitten/BSON Swift软件包,但是在遵循README指令的同时,我无法访问已创建的Document
上的任何值。
编译器无法使用该值。
let data: Document = [ "type": "createSession" ]
let type = String(data["type"])
// ^ No exact matches in call to initializer
print(type);
如果我添加一个断点并使用lldb观察该值,则它确实具有调试器输出,因此数据存在:
(lldb) vo data
(BSON.Document) data = ▿ ["type": "createSession"]
▿ storage : ByteBuffer (...)
我仍在学习Swift,看来该库实现了许多高级概念,但我仍然不确定如何正确解包。
我在做什么错了?
解决方法
REAMDE似乎已经过时且信息不正确。
正确解码Document
的一种方法涉及使用BSONDecoder().decode(type,from)
,例如:
struct Message: Codable {
let type: String;
}
let data: Document = [ "type": "createSession" ]
do {
let message = try BSONDecoder().decode(Message.self,from: Document(data: data))
print(message.type);
// This should work
} catch {
print("error is \(error.localizedDescription)")
}