我有一个数组
var friendsListGroupedFiltered = [Object]()
这种结构
struct Object {
var letters : String
var sectionObjects : [Friend]
}
包含另一个结构的对象数组
struct Friend {
let name: String
let image: UIImage?
let likes: Int
let isLiked: Bool
}
extension Friend: Equatable {
static func == (lhs: Friend, rhs: Friend) -> Bool {
return lhs.name == rhs.name
}
}
准确地说,我想为搜索栏创建过滤器功能。 我这样尝试过
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
guard !searchText.isEmpty else {
friendsListGroupedFiltered = friendsListGrouped
tableView.reloadData()
return
}
friendsListGroupedFiltered = friendsListGroupedFiltered.filter {
$0.sectionObjects.filter {
$0.name.range (of: searchText, options: .caseInsensitive) != nil
}
}
tableView.reloadData()
}
并得到一个错误
无法将类型为[[Friend]]的值转换为结束结果类型为“布尔”
array friendsListGroupedFiltered数组看起来像这样
[Object(
letters: "А",
sectionObjects: [
Friend(name: "Августин", image: Optional(<UIImage: 0x600000d3ab50>, {200, 200}), likes: 20, isLiked: false),
Friend(name: "Акакий", image: Optional(<UIImage: 0x600000d3ab50>, {200, 200}), likes: 20, isLiked: false),
Friend(name: "Алёша", image: Optional(<UIImage: 0x600000d3ab50>, {200, 200}), likes: 20, isLiked: false),
Friend(name: "Армэн", image: Optional(<UIImage: 0x600000d3ab50>, {200, 200}), likes: 20, isLiked: false)
]
),
Object(
letters: "В",
sectionObjects: [
Friend(name: "Вася", image: Optional(<UIImage: 0x600000d3ab50>, {200, 200}), likes: 20, isLiked: false)
]
),
Object(
letters: "К",
sectionObjects: [
Friend(name: "Коловрат", image: Optional(<UIImage: 0x600000d3ab50>, {200, 200}), likes: 20, isLiked: false)
]
)
等
如何通过包含在另一个结构的对象的另一个数组中的“名称”对数组进行排序?
答案 0 :(得分:0)
filter
的结果是已过滤对象的数组([Friend]
),但过滤闭包的结果是Bool
。
这就是错误消息告诉您的内容。
您可以检查过滤后的数组是否不为空,但最好是contains
friendsListGroupedFiltered = friendsListGrouped.filter {
$0.sectionObjects.contains {
$0.name.range (of: searchText, options: .caseInsensitive) != nil
}
}