问题描述
调用Decodable
需要使用addDocument(from:)
协议,因为对class PersonalInfo: Codable,ObservableObject {
@Published var name: String
@Published var age: Int
@Published var Sex: String
enum CodingKeys: CodingKey{
case name,age,Sex
}
init(name: String,age:Int,Sex:String) {
self.name = name
self.age = age
self.Sex = Sex
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self,forKey: .name)
age = try container.decode(Int.self,forKey: .age)
Sex = try container.decode(String.self,forKey: .Sex)
}
public func encode( to encoder: Encoder) throws{
var container = try encoder.container(keyedBy: CodingKeys.self)
try container.encode(name,forKey: .name)
try container.encode(age,forKey: .age)
try container.encode(Sex,forKey: .Sex)
}
}
的调用需要可编码的对象,所以它可以保存数据,因此我传递了自定义类对象,但我不知道为什么相反需要协议。
如何通过协议?
mutating func loadData(){
let listener = query?.addSnapshotListener{ (snapShot,error ) in
guard let snapshot = snapShot else {
print("Error listening")
return
}
let userCollection = try? snapshot.documents.map{ document -> PersonalInfo in
let decoder = JSONDecoder()
if let user = try document.data(as: PersonalInfo(from: decoder)){
return user
}
else{
fatalError("unable to initialize type")
}
}
}
}
mystr='hello world'
count= sum(1 if c.lower() in 'aeIoU' else 0 for c in mystr)
#output:3
解决方法
无需为您的数据结构创建类。一个类: ObservableObject 根据数据结构接受,处理并将所需的数据(值)传递(传递)到视图中... 好消息:Firebase支持Swift Codable协议–选中此link