条件绑定的初始化程序必须具有可选类型,而不是“字符串”-iOS-Swift

时间:2018-07-10 10:23:27

标签: ios swift xcode

该错误的解决方法是什么?我尝试了发现的问题,但无法解决问题。

错误在这里:

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)
            }
        }
    }

enter image description here

我不知道如何直接添加图片。抱歉

2 个答案:

答案 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