【问题标题】:Initializer for conditional binding must have Optional type, not 'Bool'条件绑定的初始化程序必须具有 Optional 类型,而不是 'Bool'
【发布时间】:2020-06-27 18:44:56
【问题描述】:

我正在尝试从我的 firebase 数据库中获取用户。我希望所有用户都出现在表格视图上。我正在尝试创建一个字典来做到这一点,但不断收到此错误:

条件绑定的初始化器必须是 Optional 类型,而不是 'Bool'

这是我的代码:

func fetchUser() {
        Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
            
            if let dictionary = snapshot.value as? [String: AnyObject] != nil {
                let user = User()
                user.setValuesForKeysWithDictionary(dictionary)
                print(user.name!, user.email!)
            }
            print("User found")
            print(snapshot)
            
        }, withCancel: nil)
    }

【问题讨论】:

    标签: swift firebase firebase-realtime-database


    【解决方案1】:

    删除!= nil,则有可选类型

    if let dictionary = snapshot.value as? [String: AnyObject] { ...
    

    【讨论】:

      【解决方案2】:

      像这样修改你的代码

      func fetchUser() {
          Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
              
              guard let dictionary = snapshot.value as? [String: AnyObject] else{ return }
                  let user = User()
                  user.setValuesForKeysWithDictionary(dictionary)
                  print(user.name!, user.email!)
              }
              print("User found")
              print(snapshot)
              
          }, withCancel: nil)
         }
       } 
      

      【讨论】:

        猜你喜欢
        • 2015-10-19
        • 2016-09-15
        • 1970-01-01
        • 1970-01-01
        • 2019-08-28
        • 2021-04-26
        • 2016-01-27
        • 2018-03-05
        • 1970-01-01
        相关资源
        最近更新 更多