【问题标题】:Realm IOS casting the Results of closureRealm IOS 铸造关闭的结果
【发布时间】:2017-08-29 04:51:19
【问题描述】:

我有一个类似的领域声明

let foundFruits = try!  Realm().objects(fruits.self).filter("color = 'red'")

我在 Tableview 中使用的结果 . . .

let fruit = foundFruits[indexPath.row]
cell.color.text = fruit.color

。 . . 现在我做第二个声明,比如

let foundFruits = try!  Realm().objects(fruits.self).filter({ $0.weight > o.7 $0.maxweight })

但由于关闭,我得到了错误

无法分配类型的值 'LazyFilterBidirectionalCollection>' 输入 '结果'

如何转换第二条语句的结果,以便将其用于我的 tableview??

【问题讨论】:

    标签: swift closures realm


    【解决方案1】:

    你想要达到的目标是不可能的。 Realm 不提供自定义过滤器块的功能,因此如果您想保留自动更新 Results 类型的查询,您需要使用 NSPredicate 来过滤结果。但是,您只能在 NSPredicates 中使用常量或键路径进行比较,因此 "weight > 0.7*maxWeight" 会导致谓词无效。

    一种可行的解决方法似乎是为您的对象类创建一个计算属性,其值为 0.7*maxWeight,但 Realm doesn't support computed properties in queries 也是。

    您想要实现的过滤只能使用 Swift 内置的 filter 方法,但是如您所见,使用 Swift 内置过滤器的返回类型不会是Results

    如果你真的需要这个谓词,目前一个可行的解决方法是将结果存储在一个 Swift 数组中,并在每次需要使用它时更新该数组。您可以将foundFruits 声明为Array<Fruit> 类型的计算属性,这样当您尝试访问它时,它会自动更新(即使性能可能会比Results 差,因为使用此,每次访问 `foundFruits 时都需要运行查询)。

    这是,如何实现解决方法:

    var foundFruits: Array<Fruit> {
        return Array(try! Realm().objects(Fruit.self).filter({Double($0.normalWeight) > 0.7*Double($0.maxWeight)}))
    }
    
    print(foundFruits)
    

    还要确保您符合 Swift 命名约定,即类名的大写字母。为此,我已将您的 fruits 类重命名为 Fruit,在您的项目中使用这段代码时请记住这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      相关资源
      最近更新 更多