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

Posted

技术标签:

【中文标题】条件绑定的初始化程序必须具有可选类型,而不是“字符串” - ios - swift【英文标题】:Initializer for conditional binding must have Optional type, not 'String' - ios - swift 【发布时间】:2018-07-10 10:23:26 【问题描述】:

这个错误的解决方法是什么?我尝试了我找到的东西,但我无法解决我的问题。

错误在这里:

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

我不知道如何直接添加图片。对不起

【问题讨论】:

Auth.auth().currentUser!.uid 显然,这不是可选的,所以if let someLetName = someNonOptionalVar 应该会抛出该错误。我认为您的意思是 let uid = Auth.auth().currentUser?.uid,因为可能未设置用户,这可能会导致崩溃(以及您在展开时避免的情况)。 【参考方案1】:

因为 Auth.auth().currentUser!.uid 返回的是 String,而不是 String?。如果要执行条件检查,则应使用

if let uid = Auth.auth().currentUser?.uid 
     //Logic here

如果你想将 Auth.auth().currentUser!.uid 的值赋给 uid,你应该在别处进行,而不是在 if 语句中

【讨论】:

【参考方案2】:

if-let/var 语句的 let uid = Auth.auth().currentUser!.uid 部分返回 String 而不是 String?。你强制解包currentUser 将其更改为currentUser?.uid

【讨论】:

以上是关于条件绑定的初始化程序必须具有可选类型,而不是“字符串” - ios - swift的主要内容,如果未能解决你的问题,请参考以下文章

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

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

条件绑定的初始化程序必须具有可选类型,而不是“字符串”在干净构建后不起作用

ios:条件绑定的初始化程序必须具有可选类型,而不是“LOTAnimationView”

条件绑定的初始化程序必须具有可选类型,而不是 '[NSObject: AnyObject]' SwiftyJSON [重复]

条件绑定的初始化程序必须具有可选类型,而不是“UIView”