该错误的解决方法是什么?我尝试了发现的问题,但无法解决问题。
错误在这里:
if var post = currentData.value as? [String : Any], let uid = Auth.auth().currentUser!.uid {
完整代码:
func incrementLikes(postId: String, onSucess: @escaping (Post) -> Void, onError: @escaping (_ errorMessage: String?) -> Void) {
let postRef = Api.Post.REF_POSTS.child(postId)
postRef.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in
if var post = currentData.value as? [String : Any], let uid = Auth.auth().currentUser!.uid {
var likes: Dictionary<String, Bool>
likes = post["likes"] as? [String : Bool] ?? [:]
var likeCount = post["likeCount"] as? Int ?? 0
if let _ = likes[uid] {
likeCount -= 1
likes.removeValue(forKey: uid)
} else {
likeCount += 1
likes[uid] = true
}
post["likeCount"] = likeCount as AnyObject?
post["likes"] = likes as AnyObject?
currentData.value = post
return TransactionResult.success(withValue: currentData)
}
return TransactionResult.success(withValue: currentData)
}) { (error, committed, snapshot) in
if let error = error {
onError(error.localizedDescription)
}
if let dict = snapshot?.value as? [String: Any] {
let post = Post.transformPostPhoto(dict: dict, key: snapshot!.key)
onSucess(post)
}
}
}
我不知道如何直接添加图片。抱歉
答案 0 :(得分:1)
因为Auth.auth()。currentUser!.uid返回一个String,而不是String?。如果要执行条件检查,则应使用
if let uid = Auth.auth().currentUser?.uid {
//Logic here
}
如果要将Auth.auth()。currentUser!.uid的值分配给uid,则应在其他地方而不是在if语句中进行
答案 1 :(得分:0)
您的let uid = Auth.auth().currentUser!.uid
语句的if-let/var
部分返回String
而不是String?
。您被迫解开currentUser
并将其更改为currentUser?.uid