微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

过滤结构体

如何解决过滤结构体

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

@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搜索String

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。