例如:
class Test {
var name: String;
var age: Int;
var height: Double;
func convertToDict() -> [String: AnyObject] { ..... }
}
let test = Test();
test.name = "Alex";
test.age = 30;
test.height = 170;
let dict = test.convertToDict();
Run Code Online (Sandbox Code Playgroud)
dict将有内容:
{"name": "Alex", "age": 30, height: 170}
Run Code Online (Sandbox Code Playgroud)
这在Swift中可能吗?
我可以像字典一样访问类,例如可能使用:
test.value(forKey: "name");
Run Code Online (Sandbox Code Playgroud)
或类似的东西?
谢谢.
主要是我的用例是使用字典创建对象:例如
struct Person: Codable { let name: String }
let dictionary = ["name": "Bob"]
let person = Person(from: dictionary)
Run Code Online (Sandbox Code Playgroud)
我想避免编写自定义实现,并希望尽可能高效.
我对 Firebase 的新 Cloud Firestore 相对较新,并且在尝试将数据映射到/从时遇到困难。我已经尝试通过 Google 在线查看文档,但它有一些我无法弄清楚的问题。
[String : Any]自定义结构转换时,文档建议我尝试以下操作:docRef.getDocument { (document, error) in
let result = Result {
try document.flatMap {
try $0.data(as: City.self)
}
}
switch result {
case .success(let city):
if let city = city {
print("City: \(city)")
} else {
print("Document does not exist")
}
case .failure(let error):
print("Error decoding city: \(error)")
}
}
Run Code Online (Sandbox Code Playgroud)
然而,这产生就行错误$0.data(as: City.self)与类型的值“NSObject的”没有成员“数据”。
do {
try db.collection("cities").document("LA").setData(from: city)
} catch let error {
print("Error …Run Code Online (Sandbox Code Playgroud)