I got this code:
let arrData = [["id": "1",
"name": "Apple",
"category": "Fruit"],
["id": "2",
"name": "Pie",
"category": "Fruit"],
["id": "3",
"name": "Tomato",
"category": "Vegetable"]]
let categorieNames = Array(Set(arrData.map({$0["category"]!})))
var arrResult:[[String]] = []
for i in 0..<categorieNames.count {
let categories = arrData.filter({$0["category"] == categorieNames[i]}).map({$0["name"]!})
arrResult.append(categories)
}
print("result : \(arrResult)")
it works perfectly with an Array. But now I get my data from a json:
[{"id":"1",
"name":"Apple",
"category":"Fruits"},
{"id":"2",
"name":"Pie",
"category":"Fruits"},
{"id":"3",
"name":"Tomato",
"category":"Vegetable"}]
here is my struct and my decode function:
struct MarketStruct : Decodable {
let id : Int?
let name : String?
let category : String?
}
class MarketsCollectionViewController: UICollectionViewController, NetworkDelegate {
var myMarkets : [MarketStruct]?
var categorieNames : [Any] = []
var categorieArray:[[String]] = []
func didFinish(result: Data) {
do {
self.myMarkets = try JSONDecoder().decode([MarketStruct].self, from: result)
categorieNames = Array(Set(myMarkets!.map({ ["category": $0] })))
for i in 0..<categorieNames.count {
let categories = myMarkets!.filter({$0["category"] == categorieNames[i]}).map({["name": $0]!})
categorieArray.append(categories)
}
} catch let jsonErr {
print("Error:", jsonErr)
}
self.myCollectionView.reloadData()
}
I got an error at the filter part: Type 'MarketStruct' has no subscript members
what must I change that the above Array code works with my JSON array?
thanks for your help.
edit my current code:
self.myMarkets = try JSONDecoder().decode([MarketStruct].self, from: result)
categorieNames = Array(Set(myMarkets.map({$0.category })))
for i in 0..<categorieNames.count {
let categories = myMarkets!.filter({$0.category == categorieNames[i]}).map({$0.name})
categorieArray.append(categories as! [String])
}
} catch let jsonErr {
print("Error:", jsonErr)
}
self.myCollectionView.reloadData()
it compiles with error: Command failed due to signal: Segmentation fault: 11
if I comment categorieNames = Array(Set(myMarkets.map({$0.category }))) out it compiles without errors
myMarkets!.filter({$0.category...instead? Because$0is now aMarketStruct, so to accesscategory, you just have to domyMarketStruct.category. But when you did previouslylet categories = arrData.filter({$0["category"],$0was a Dict, so to access thecategory, you need to do["category"](that's a subscript).struct,idis aInt, but in the JSON you gave, it's aString. You should get an error. Else,categorieNames2 = Array(Set(myMarkets.flatMap({$0.category})))could fix your issue (because you have optionals stuff I think). and the first time you didmap({$0["category"]!}notmap({["category":$0]!}that's not the same type of data and doesn't match with you declaration, and after you docategorieNames[i], which you expect to be a String.