Reputation: 65
What is the solution to this error? I tried what I found, but I could not sort out my problem.
Error is here:
if var post = currentData.value as? [String : Any], let uid = Auth.auth().currentUser!.uid {
Full Code:
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)
}
}
}
I do not know how to add a picture directly. Sorry
Upvotes: 0
Views: 103
Reputation: 623
Because Auth.auth().currentUser!.uid returns a String, not String?. If you want to perform a conditional check, you should use
if let uid = Auth.auth().currentUser?.uid {
//Logic here
}
If you want to assign value of Auth.auth().currentUser!.uid to uid, you should do it elsewhere, not inside an if statement
Upvotes: 1
Reputation: 515
The let uid = Auth.auth().currentUser!.uid
part of your if-let/var
statement returns a String
instead of an String?
. You're force unwrapping currentUser
Change it to currentUser?.uid
Upvotes: 0