[英]How to filter an array of generic type in iOS
我有一個函數,我要向它發送一組對象。 我想要做的是使用它們的值過濾這個對象數組,因為對象可能沒有名稱、年齡等通用屬性。
func searchVC<T>(_ searchCriteria: String, _ modelArray: [T]) {
let filteredArrayOfDict = modelArray.filter { $0.value == searchCriteria }
}
但是,這給了我以下錯誤:
Value of type 'T' has no member 'value'
我的模型類是這樣的:
class ABC : Mappable, CustomStringConvertible {
public private(set) var name : String?
public private(set) var age : Int?
public private(set) var abcArray : [ABCModelArray]
required init?(map: Map){
name = ""
age = -1
mapping(map: map)
}
func mapping(map: Map) {
name <- map["Name"]
age <- map["Age"]
}
public var description: String{
}
}
class EFG : Mappable, CustomStringConvertible {
public private(set) var type : String?
public private(set) var code : Int?
public private(set) var efgArray : [EFGModelArray]
required init?(map: Map){
type = ""
code = -1
mapping(map: map)
}
func mapping(map: Map) {
type <- map["Type"]
code <- map["Code"]
}
public var description: String{
}
}
如何實現?
既然你自己說過,這些對象可能沒有共同的屬性,你不能使用普通的泛型來做到這一點。 您需要將其限制為某種協議。 例如 :
protocol Filterable {
var filterableValue: String
}
然后你的方法看起來像這樣:
func searchVC(_ searchCriteria: String, _ modelArray: [Filterable]) {
let filteredArrayOfDict = modelArray.filter { $0.filterableValue == searchCriteria }
}
您當然需要通過所有可以在此處傳遞的對象來遵守此協議,並為每個對象返回適當的filterableValue
。
是的,但您需要使您的類型符合HasValue
protocol HasValue {
var value: String { get }
}
例子
struct Person: HasValue {
let firstName: String
let age: Int
var value: String { return firstName }
}
現在你可以定義你的函數
func filter<Element:HasValue>(list: [Element], byKeyword keyword: String) -> [Element] {
return list.filter { $0.value == keyword }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.