gpt4 book ai didi

arrays - 如何过滤包含字符串的数组和结构体对象数组,其中有字符串参数?

转载 作者:行者123 更新时间:2023-11-30 11:00:11 30 4
gpt4 key购买 nike

我有一个数组

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()
}

并出现错误

Cannot convert value of type '[Friend]' to closure result type 'Bool'

数组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)
]
)

等等
如何按“名称”对包含在另一个结构的另一个对象数组中的数组进行排序?

最佳答案

filter 的结果是过滤对象的数组 ([Friend]),但过滤闭包的结果是 Bool

这就是错误消息告诉您的内容。

您可以检查过滤后的数组是否不为空,但更好的是contains

friendsListGroupedFiltered = friendsListGrouped.filter {
$0.sectionObjects.contains {
$0.name.range (of: searchText, options: .caseInsensitive) != nil
}
}

关于arrays - 如何过滤包含字符串的数组和结构体对象数组,其中有字符串参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53471531/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com