Here's what I am trying to do:
I am starting with an array of ArticleItem objects. Those objects have a property on them named 'category' which is a string. I'm trying to loop through all of my ArticleItem objects and group items with like categories in a dictionary. I'm using the category name as my key. The issue I am having is that my dictionary keys are hold arrays that never contain more than 1 object. I definitely have more than 3 objects with the same category name. Here is the relevant code from my class. I'd love to understand the right way to do this..
private var _articlesDict:[String:[ArticleItem]]
init(articles:[ArticleItem]) {
_articlesDict = [String:[ArticleItem]]()
for item:ArticleItem in articles {
var optionalCatArray:[ArticleItem]? = _articlesDict[item.category]
if let catArray = optionalCatArray {
optionalCatArray!.append(item) //why can't I do catArray.append(item)?
} else {
var arr:[ArticleItem] = [ArticleItem]()
arr.append(item)
_articlesDict[item.category] = arr
}
}
}