问题描述
我有一个以下结构的数组,我想用搜索栏中的给定文本对其进行过滤:
@State private var presentAccounts : [Followee] = []
struct Followee {
public let userName : String
public let uuid : String
public let firstName : String
public let lastName : String
public let placesCount : String
}
ForEach(self.presentAccounts.indices,id:\.self) { i in
FolloweePresent(user: self.presentAccounts[i])
}
struct FolloweePresent : View {
@State var user : Followee
var body: some View {
HStack {
Image("defPerson").resizable().frame(width: 45,height: 45)
vstack(alignment: .leading) {
Text(user.userName).font(Font.custom("Quicksand-Bold",size: 17)).foregroundColor(Color.gray)
HStack{
Text("\(user.firstName) \(user.lastName)").font(Font.custom("Quicksand-Medium",size: 15)).foregroundColor(Color.gray)
Circle().fill(Color.gray).frame(width: 7,height: 7)
Text("\(user.placesCount) spots saved").font(Font.custom("Quicksand-Medium",size: 15)).foregroundColor(Color.gray)
}
}
Spacer()
Image(systemName: "chevron.right").frame(width: 10)
}.padding().frame(height: 60)
}
}
@State var searchText : String = ""
HStack{
if searchText == "" {
Image(systemName: "magnifyingglass").foregroundColor(.black)
}
TextField("search",text: $searchText)
if searchText != "" {
Button(action: {
self.searchText = ""
},label: {
Text("cancel")
})
}
}.padding(.horizontal).frame(height: 36).background(Color("GrayColor")).cornerRadius(5)
我想用搜索栏中的searchText过滤数组(userName,firstName和lastName),但似乎无法使其与.filter($ 0)一起使用,我该怎么办?
解决方法
这是有关如何过滤的好例子
var items: [Followee] = []
items = items.filter { (item: Followee) in
// with the help of the `item`,tell swift when to
// get rid of an item and when to keep it
// if the item is an item that should be kept,return true
// if you don't want the item,return false
// for example if you don't need items that their usernames contain "*",you can do this:
if item.userName.contains("*") {
// the item is not allowed,get rid of it!
return false
}
else {
// the item is aloowed,so keep it!
return true
}
}