我有一个单元格模型
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
}
}
AND
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] \($0)" }.joined(separator: " || ")
let predicate = NSPredicate(format: query)
let results = self.items.filter { predicate.evaluate(with: $0) }
但是我遇到了运行时崩溃
2018-08-08 00:38:01.787170 + 0530 BeerCrafts [3388:401950] *** 由于未捕获的异常“ NSUnknownKeyException”而终止应用程序, 原因:'[<_SwiftValue 0x60400064dce0> valueForUndefinedKey:]:此 类别不符合密钥啤酒的密钥值编码要求。'
数组或谓词有什么问题?
更新:添加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
}
答案 0 :(得分:3)
此时,无需处理arr = [true, false, false, true, false]
,Chai.expect(_.filter(arr, item => item == true)).to.have.length(2)
方法足以满足您的情况,例如:
NSPredicate
filter
是let filtered = items.filter { value.contains($0.beer.style) }
的数组,其中应包含其filtered
是BeerCellModel
数组元素之一的对象。
答案 1 :(得分:3)
您可以尝试
let value = ["tuborg", "budwiser", "bira"]
let query = value.map { "self CONTAINS[cd] '\($0)'" }.joined(separator: " || ")
let predicate = NSPredicate(format: query)
let results = self.items.filter { predicate.evaluate(with: $0.beer.style) }
答案 2 :(得分:1)
看起来您正在尝试映射String
数组,而不是BeerCellModel
结构数组。