struct User{
var firstName:String
var lastName:String
var city:String
var email:String
}
var users = [User]
我正在尝试过滤用户,因为有人在文本字段中键入内容。就像搜索电子邮件一样。它应该显示所有匹配的结果,但不能复制同一用户。我能够基于一个属性,例如name
来过滤数组,但是不确定如何根据所有属性来过滤数组。
我已经实现了UITextField委托,并具有用于过滤的代码。
let filteredArray = users.filter({ (user) -> Bool in
return user.firstName.lowercased().contains(“John”)
})
答案 0 :(得分:3)
let filteredArray = users.filter({ $0.firstName.lowercased().contains("firstName") || $0.lastName.lowercased().contains("lastName") || ... })
答案 1 :(得分:2)
您可以设置多个条件,并将它们与OR(||)或AND(&&)组合在一起-它是一个简单的布尔值,您可以将其视为if语句中的内容-
if user.firstName.lowercased().contains("john") || user.lastName.lowerCased().contains("lastname") { return true }
else { return false }
所以在您的代码中它将像
let filteredArray = users.filter { (user) -> Bool in
return user.firstName.lowercased().contains("john") || user.lastName.lowercased().contains("lastname") }
答案 2 :(得分:1)
由于您可能需要搜索多个内容,因此建议您制作一个Searchable
协议,并通过检查其组成部分是否匹配来使聚合类型可搜索。
import Foundation
struct User {
let firstName: String
let lastName: String
let city: String
let email: String
let age: Int // an example of a non-String type.
}
protocol Searchable {
func matches(query: String) -> Bool
}
extension String: Searchable {
func matches(query: String) -> Bool {
// Implement any kind of searching algorithm here. Could be as smart as fuzzy seraching
// or as basic as this case-insenitive simple substring search
return self.lowercased().contains(query)
}
}
extension Int: Searchable {
func matches(query: String) -> Bool {
return String(self).matches(query: query)
}
}
extension User: Searchable {
func matches(query: String) -> Bool {
let constituents: [Searchable] = [firstName, lastName, city, email, age]
return constituents.contains(where: { $0.matches(query: query) })
}
}