【问题标题】:Cannot convert value of type Int to expected argument type Bool无法将 Int 类型的值转换为预期的参数类型 Bool
【发布时间】:2016-12-20 03:08:03
【问题描述】:

我正在尝试使用三个条件过滤 Firebase 查询结果:

let posts = snapshot.childSnapshots.map {
                    Post(snapshot: $0)
                    }.reversed().filter {
                        post?.isGlobal == dataFilter && (self.dependents.contains($0.postedBy) || self.currentUser?.uid == $0.postedBy)
                }

必须满足第一个条件(post.isglobal == datafilter)。然后,我想在满足其余两个条件之一时进一步过滤帖子。

以上代码返回错误:Binary operator == cannot be applied to operands of type NSNumber? and Int

任何帮助将不胜感激。 谢谢!

编辑:dataFilter 变量被定义为 viewcontroller 类中的全局变量:

var dataFilter = 0

【问题讨论】:

  • 比较是用==,而不是=
  • 如果我把它改成==我得到错误Binary operator == cannot be applied to operands of type NSNumber? and Int
  • 尝试 (post?.isGlobal.intValue ?? 0) == 或在访问其 isGlobal intValue 属性之前打开您的可选帖子
  • 谢谢利奥!那行得通。那做了什么?是否将其转换为 Int,然后如果找不到该值则将其设置为 0?

标签: ios swift firebase swift3 firebase-realtime-database


【解决方案1】:

您可以打开您的可选帖子并访问它的 isGlobal intValue 属性,NSNumber 有一个 intValue 属性,它返回一个 Int,您可以将其与您的 dataFilter (Int) 值进行比较。或使用'??' nil 合并以解开您的可选绑定,同时为它提供一个默认值以防出现 nil。

所以如果你打开你的帖子对象:

post.isGlobal.intValue == dataFilter

或者使用可选的 biding 和 nil 合并操作符:

(post?.isGlobal.intValue ?? 0) == dataFilter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-03
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    相关资源
    最近更新 更多