iOS Swift 使用 NSPredicate 过滤数组在 运行 时崩溃

iOS Swift Filter Array using NSPredicate crashing on run time

我有手机型号

struct BeerCellModel: Hashable {

    var beer: Beer

    static func == (lhs: BeerCellModel, rhs: BeerCellModel) -> Bool {
        return lhs.beer.id == rhs.beer.id
    }

    var hashValue: Int {
        return self.beer.id
    }
}

public struct Beer {
    public var abv: String
    public var ibu: String
    public var id: Int
    public var name: String
    public var style: String
    public var ounces: Int
}

现在我有一个数组名称 'items = [BeerCellModel]' 上面的单元格模型,我正在用参数 style

过滤数组
let value = ["tuborg", "budwiser", "bira"]
let query = value.map { "SELF.beer.style CONTAINS[cd] \([=15=])" }.joined(separator: " || ")
let predicate = NSPredicate(format: query)
let results = self.items.filter { predicate.evaluate(with: [=15=]) }

但我遇到了 运行 时间崩溃

2018-08-08 00:38:01.787170+0530 BeerCrafts[3388:401950] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<_SwiftValue 0x60400064dce0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key beer.'

数组或谓词有什么问题?

更新:添加 JSON 响应 Beer

  {
    "abv": "0.08",
    "ibu": "35",
    "id": 11,
    "name": "Monks Blood",
    "style": "Belgian Dark Ale",
    "ounces": 12
  },
  {
    "abv": "0.07",
    "ibu": "65",
    "id": 10,
    "name": "Brew Free! or Die IPA",
    "style": "American IPA",
    "ounces": 12
  },
  {
    "abv": "0.04",
    "ibu": "17",
    "id": 9,
    "name": "Hell or High Watermelon Wheat",
    "style": "Fruit / Vegetable Beer",
    "ounces": 12
  }

看起来您正在尝试映射一个 String 数组,而不是一个 BeerCellModel 结构数组。

此时不需要处理NSPredicatefilter方法足以满足你的情况,如:

let filtered = items.filter { value.contains([=10=].beer.style) }

filteredBeerCellModel 的数组,其中应包含其 beer.stylevalue 数组元素之一的对象。

你可以试试

let value = ["tuborg", "budwiser", "bira"]
let query = value.map { "self CONTAINS[cd] '\([=10=])'" }.joined(separator: " || ")
let predicate = NSPredicate(format: query)
let results = self.items.filter { predicate.evaluate(with: [=10=].beer.style) }