[英]How can I sort a class using an array? - swift 5
I've a class called "cars":我有一个名为“汽车”的课程:
car1 = [name: "ferrari", color: "black", size: "small" ]
car2 = [name: "Lamborghini", color: "orange", size: "small" ]
car3 = [name: "Audi", color: "black", size: "big" ]
car4 = [name: "fiat", color: "yellow", size: "small" ]
car5 = [name: "ferrari", color: "red", size: "medium" ]
and made a list of them:并列出了它们:
list = [car1,car2,car3,car4]
and now I want to sort/filter this list.现在我想对这个列表进行排序/过滤。
If I try filtering it using a string, everything works fine:如果我尝试使用字符串对其进行过滤,则一切正常:
let searchtext = "Audi"
filteredlist = list.filter({ $0.name.lowercased().contains(searchText.lowercased()) })
--> filteredlist = [car3] //result
but I want to use an array, so them I could have more results shown.但我想使用一个数组,这样我就可以显示更多结果。 Something like filtering by more than one color (similar to an "or" condition in an "if statement").
类似于通过多种颜色过滤(类似于“if 语句”中的“或”条件)。
I've tried the same struct (but of course didn't work):我尝试过相同的结构(但当然没有用):
let searchtext = ["black","red"]
filteredlist = list.filter({ $0.color.contains(searchText) })
--> filteredlist = [car1,car3,car5] //expected, got compilation error instead
I'm having these errors:我有这些错误:
Cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
Instance method 'contains' requires that '[String]' conform to 'StringProtocol'
I can think in 2 solutions (that aren't the ideal ones) to solve this need:我可以想到 2 个解决方案(不是理想的解决方案)来解决这个需求:
1 - create a while/for function and filter the list for each element of the searchtext array and unite everything in the end (not recommended because I will have to read the list 'n' times ) 1 - 创建一个 while/for 函数并为 searchtext 数组的每个元素过滤列表,最后将所有内容统一起来(不推荐,因为我将不得不阅读列表“n”次)
update:stupid way更新:愚蠢的方式
var i = 0
var listapp: [Item] = []
while i < searchtext.count {
listapp.append(contentsOf: list.filter({ $0.tipo.contains(searchtext[i]) }))
i += 1
}
list = listapp
2 - manually filtering the list using 'if','or','while' instead of using list.filter function 2 - 使用 'if','or','while' 手动过滤列表,而不是使用 list.filter 函数
The other way round:反过来说:
let searchtext = ["black","red"]
filteredlist = list.filter({ searchtext.contains($0.color) })
A double contains
should do it:双
contains
应该这样做:
let searchText = ["black", "red"].map { $0.lowercased() }
filteredlist = list.filter { item in
let color = item.color.lowercased()
return searchText.contains { text in color.contains(text) }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.