Swiftui 过滤结构数组

Swiftui 过滤结构数组,swiftui,swiftui-list,Swiftui,Swiftui List,我有一个以下结构的数组,我想用搜索栏中的给定文本对其进行过滤: @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 pl

我有一个以下结构的数组,我想用搜索栏中的给定文本对其进行过滤:

@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
循环显示用户,如下所示:

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
搜索
字符串的搜索栏

@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)


我想使用搜索栏中的搜索文本(用户名、名字和姓氏)筛选数组,但似乎无法使其与.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
        }
    }

谢谢如何检查一个字符串是否包含在另一个字符串中?(而不是item.count==0)使用稍微更改的更好的示例更新了答案