简体   繁体   中英

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").

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:

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 )

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

The other way round:

let searchtext = ["black","red"]
filteredlist = list.filter({ searchtext.contains($0.color) })

A double contains should do it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM