大家周日快乐。我在解码数据时遇到了一个问题。当我将字典字符串序列化为一个对象时,我似乎无法解码数据。我试图从firebase中获取匹配项,这在获取用户配置文件时有效,但在获取匹配项时无效。
func fetchMatches(onCompletion: @escaping (Result<[MatchModel], DomainError>) -> ()){
db.collection("matches").whereField("usersMatched", arrayContains: userId!).getDocuments(completion: {doc, err in
guard let documentSnapshot = doc, err == nil else{
onCompletion(.failure(.downloadError))
return
}
var matchList: [MatchModel] = []
var count = 0
let maxCount = documentSnapshot.documents.count
var hasFailed = false
for document in documentSnapshot.documents{
if hasFailed{ break }
let decoder = JSONDecoder()
var dict = document.data()
for (key, value) in dict {
if let value = value as? Timestamp {
let formatter = DateFormatter()
let newValue = value.dateValue()
formatter.dateStyle = .short
formatter.timeStyle = .none
dict[key] = formatter.string(from: newValue)
}
}
到这里为止,我知道一切都很顺利。字典包含-
Dictionary
["timestamp": "10/22/22", "usersMatched": <__NSArrayM 0x600002c61680>(
6euZHDmI7PMDcCmft5MfxUW27jI3,
tbcB0ay0YEgZcY9UsZ00WjZ9h893
)
]
下面的数据打印出105个字节,因此根据这些信息,我知道它不是空的,并且JSONSerialization完成了将dict转换为对象的工作。
if let data = try? JSONSerialization.data(withJSONObject: dict, options:[]){
do{
let match = try? decoder.decode(FirestoreMatch.self, from: data)
let matchId : String = match!.usersMatched.filter{$0 != self.userId!}.first!
... }
catch{
print(error)
错误返回:
typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "timestamp", intValue: nil)], debugDescription: "Expected to decode Double but found a string/data instead.", underlyingError: nil))
这是我的FirestoreMatch结构体
struct FirestoreMatch: Codable{
let usersMatched: [String]
let timestamp: Date
}
我的结构体需要更多的信息吗?我不知道为什么match返回nil
1条答案
按热度按时间wnavrhmk1#
感谢@itaiFerber、@flanker、@loremipsum和@duncanC,我能够通过利用