【发布时间】:2021-03-25 22:45:19
【问题描述】:
我正在尝试过滤具有数组的结构数组。以下是我正在使用的数据结构。我也想过滤内部数组,但它不起作用
var objects = [SomeObject]() //array of objects
var filteredObject = [SomeObject]() //filtered array
var isSearching = false
struct SomeObject {
var sectionName: String
var sectionObjects : [History]
}
struct History {
var firstName: String
var lastName: Int
}
func searchBar(_ text: String) {
filteredObject = objects.filter({ (obj: SomeObject) -> Bool in
return obj.sectionObjects.filter { $0.firstName.contains(text.lowercased())}.isEmpty
})
print("====", filteredObject, "fill===")
}
let history = History(firstName: "John", lastName: 1)
let anotherHistroy = History(firstName: "Dee", lastName: 2)
let historyArray = [history, anotherHistroy]
let newObject = SomeObject(sectionName: "Section 1", sectionObjects: historyArray)
objects.append(newObject)
searchBar("Jo") // printing of filtered object should not have another history in it's sectionObjects
【问题讨论】:
-
您的示例中的 desired 输出是什么,为什么?
-
==== [test.SomeObject(sectionName: "Section 1", sectionObjects: [test.History(firstName: "John", lastName: 1), test.History(firstName: "Doe", lastName: 2)])] fill===这是objects的内容,这意味着第二个过滤器不起作用。如果sectionObjects包含searchText,它将返回整个结构而不是过滤它 -
但没有一个包含“Jn”。那么为什么要过滤掉任何东西呢?
-
history'sfirstnameJohn包含 Jn -
我看不到它包含在哪里。它有一个
J和一个n,但它没有Jn。问题是你不知道contains是什么意思吗?尝试打印出"John".contains("Jn")的结果。你会发现它是假的。它不包含它(在任何意义上,Swift 或我都知道)。