[英]How to filter one array into multiple arrays depending on a specific value inside of the array?
I am trying to filter an array of places into multiple arrays depending on the city, state (which I have labeled as address) of the place.我正在尝试根据地点的城市、州(我已标记为地址)将地点数组过滤成多个数组。 I want all of the place objects with the same address to be grouped into one array so I can use that address as a header for each section in my tableView.
我希望将具有相同地址的所有地点对象分组到一个数组中,这样我就可以将该地址用作 tableView 中每个部分的标题。 I just don't know how to do it.
我只是不知道该怎么做。 I am not sure how to show any code for this but I have tried
filteredPlaces.append(places.filter({ $0.address }))
That didn't work at all.我不知道如何为此显示任何代码,但我尝试
filteredPlaces.append(places.filter({ $0.address }))
这根本不起作用。
I tried to loop through the places
array, but I wasn't sure what code I needed in order to identify if any of the objects had the same address.我试图遍历
places
数组,但我不确定我需要什么代码来识别是否有任何对象具有相同的地址。
My current filteredPlaces
array looks like this: var filteredPlaces = [[Place]()]
and my current array that is holding all of the places, looks like this: var places = [Place]()
我当前的
filteredPlaces
数组如下所示: var filteredPlaces = [[Place]()]
和当前包含所有位置的数组如下所示: var places = [Place]()
How can I create separate arrays based on the address of each place in one array?如何根据一个数组中每个位置的地址创建单独的数组?
Here is my place object class这是我的地方对象类
class Place {
var name: String
var street: String
var city: String
var state: String
var zip: String
var drinks: [Drink]
var address: String {
return "\(city), \(state)"
}
init(name: String, street: String, city: String, state: String, zip: String, drinks: [Drink]) {
self.name = name.uppercased()
self.street = street.uppercased()
self.city = city.uppercased()
self.state = state.uppercased()
self.drinks = drinks
self.zip = zip
}
convenience init(name: String, street: String, city: String, state: String, zip: String, drinks: [Drink]?) {
if drinks != nil {
self.init(name: name, street: street, city: city, state: state, zip: zip, drinks: drinks)
} else {
self.init(name: name, street: street, city: city, state: state, zip: zip, drinks: [Drink]())
}
}
}
I haven't created the declaration yet because that will be done when a user enters the places on a new viewController.我还没有创建声明,因为这将在用户输入新 viewController 上的位置时完成。
You can use Dictionary(grouping:by:)
您可以使用
Dictionary(grouping:by:)
The example is like这个例子就像
/// let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
/// let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })
/// // ["E": ["Efua"], "K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"]]
In your case you need something hashable for the key of the dictionary, so a hashable pair of place and street names:在您的情况下,您需要一些可散列的字典键,因此一对可散列的地点和街道名称:
struct PlaceNameStreet: Hashable {
let name: String
let street: String
}
let dictionary = Dictionary(grouping: places) { place in
PlaceNameStreet(name: place.name, street: place.street)
}
you could try something like this, to obtain an dictionary of adresses
with Places
.您可以尝试这样的方法,以获取带有
Places
的adresses
字典。
EDIT-1: using your Place
class. EDIT-1:使用您的
Place
课程。
// example Places, 2 in Tokyo, and 3 in Sydney
var places = [
Place(name: "place-1", street: "street-1", city: "Tokyo", state: "Kanto", zip: "123", drinks: []),
Place(name: "place-2", street: "street-2", city: "Tokyo", state: "Kanto", zip: "123", drinks: []),
Place(name: "place-1", street: "street-1", city: "Sydney", state: "NSW", zip: "123", drinks: []),
Place(name: "place-2", street: "street-2", city: "Sydney", state: "NSW", zip: "123", drinks: []),
Place(name: "place-3", street: "street-3", city: "Sydney", state: "NSW", zip: "123", drinks: [])]
// just for info
let adrss = Set(places.map{$0.address})
print("\n---> unique adresses: \(adrss) \n")
// returns a dictionary where the key is the address and the value are the Places
let allPlaces: [String:[Place]] = Set(places.map{$0.address}).reduce(into: [:]) { dict, adrs in
dict[adrs] = places.filter{$0.address == adrs}
}
// an array of all places in Sydney
print("\n---> all Places in Sydney: \(allPlaces["SYDNEY, NSW"]) \n")
// an array of all places in Tokyo
print("\n---> all Places in Tokyo: \(allPlaces["TOKYO, KANTO"]) \n")
The term Set(places.map{$0.address})
gives you all unique addresses.术语
Set(places.map{$0.address})
为您提供所有唯一地址。 the .reduce(into: [:])
, accumulates the Places
for each address. .reduce(into: [:])
,累积每个地址的Places
。 The result is a dictionary, with the key=the address and the value=the array of Place
结果是一个字典,key=地址,value=
Place
的数组
Example usage:示例用法:
struct ContentView: View {
@State var allPlaces: [String:[Place]] = [:]
var body: some View {
List {
ForEach(allPlaces.keys.sorted(), id: \.self) { key in
Section(header: Text(key)) {
ForEach(allPlaces[key] ?? []) { place in
Text(place.name)
}
}
}
}
.onAppear {
// example Places, 2 in Tokyo, and 3 in Sydney
var places = [
Place(name: "place-1", street: "street-1", city: "Tokyo", state: "Kanto", zip: "123", drinks: []),
Place(name: "place-2", street: "street-2", city: "Tokyo", state: "Kanto", zip: "123", drinks: []),
Place(name: "place-1", street: "street-1", city: "Sydney", state: "NSW", zip: "123", drinks: []),
Place(name: "place-2", street: "street-2", city: "Sydney", state: "NSW", zip: "123", drinks: []),
Place(name: "place-3", street: "street-3", city: "Sydney", state: "NSW", zip: "123", drinks: [])]
// returns a dictionary where the key is the address and the value are the Places
allPlaces = Set(places.map{$0.address}).reduce(into: [:]) { dict, adrs in
dict[adrs] = places.filter{$0.address == adrs}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.