我有四个要搜索和过滤的字段。我可以单独搜索它,但是现在我想合并所有四个字段并获取结果,然后重新加载集合视图。
使用的数据模型如下:
import Foundation
// MARK: - Empty
struct SearchDataModel: Codable,Equatable {
static func == (lhs: SearchDataModel, rhs: SearchDataModel) -> Bool {
return false
}
let status: Int
var data: [Datum]
}
// MARK: - Datum
struct Datum: Codable,Equatable {
let userID: Int
let name: String
let image: String?
// let image: JSONNull?
let userAddress: String?
let id: Int
let listingImage: String?
let listingVideo: String?
let listingTitle: String
let listingAddress: String?
let listingPrice: String?
let listingType: String
let listingUse: String
let listingSqft: String?
let listingBedsCount, listingBathsCount, listingParkingSpot: Int?
let listingDescription: String
let featureListing: Int
let createdAt, updatedAt: String
enum CodingKeys: String, CodingKey {
case userID = "user_id"
case name, image
case userAddress = "user_address"
case id
case listingImage = "listing_image"
case listingVideo = "listing_video"
case listingTitle = "listing_title"
case listingAddress = "listing_address"
case listingPrice = "listing_price"
case listingType = "listing_type"
case listingUse = "listing_use"
case listingSqft = "listing_sqft"
case listingBedsCount = "listing_beds_count"
case listingBathsCount = "listing_baths_count"
case listingParkingSpot = "listing_parking_spot"
case listingDescription = "listing_description"
case featureListing = "feature_listing"
case createdAt = "created_at"
case updatedAt = "updated_at"
}
}
搜索的字段是标价,标价类型,标价用途,标价地址。
每个字段的搜索过滤器如下:
let list1 = orgsearchDataModel?.data.filter { $0.listingAddress!.range(of: keyword!, options: .caseInsensitive) != nil }
let list2 = orgsearchDataModel?.data.filter { $0.listingType.range(of: type, options: .caseInsensitive) != nil }
let list3 = orgsearchDataModel?.data.filter { $0.listingUse.range(of: use, options: .caseInsensitive) != nil }
let list4 = orgsearchDataModel?.data.filter {
if let price = Int($0.listingPrice ?? "0") {
return (price > min! && price < max!)
}
return false
}
现在获得所有四个的组合搜索结果:
let a = list1!.filter { list2!.contains($0) && list3!.contains($0) && list4!.contains($0)}
问题在于它正在将list1
与list2
和list3
组合在一起并正确显示结果,
let a = list1!.filter { list2!.contains($0) && list3!.contains($0) }
,但是当我也添加list4
时,结果为零。
有人可以帮助我如何组合所有搜索并获得满足所有四个搜索字段的结果。
答案 0 :(得分:0)
确认您的结构为Hashable并实现方法
struct Datum: Codable,Equatable, Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(userID)
hasher.combine(name)
hasher.combine(image)
//Add other values too
}
}
let result = Set(list1 ?? [])
.intersection(list2 ?? [])
.intersection(list3 ?? [])
.intersection(list4 ?? [])
let array = Array(result)