By declaring an NSDictionary and putting it a pair of key values ​​in Swift?

I am trying to declare an NSDictionary with a class type key and value as follows:

var catAndSubCatDict: NSDictionary<Category, Array<SubCategory>> = NSDictionary<Category, Array<SubCategory>>() 

Here, "Category" and "Subcategory" are global classes. I know that I cannot use the class type for the key field. However, I still have to achieve this. Is there any way to do this? How can I declare specialized NSDictionary or similar things for this?

In addition, I use this dictionary as follows:

 for(var i=0; i<resultJson.count; i++) { let subCategoryItemList = resultJson.objectAtIndex(i) as NSDictionary let categoryItem = subCategoryItemList.valueForKey(WSConstants.CATEGORY_OBJ) as NSDictionary var category: Category = Category() category.categoryId = categoryItem.valueForKey(WSConstants.CATEGORY_ID) as Int category.categoryName = categoryItem.valueForKey(WSConstants.NAME) as String var subCategoryList: Array<SubCategory> = [] let jsonSubCategoryList = subCategoryItemList.allKeysForObject(WSConstants.SUBCATEGORY_LIST_OBJ) as NSArray for(var i=0; i<jsonSubCategoryList.count; i++) { let subCategoryObj = jsonSubCategoryList.objectAtIndex(i) as NSDictionary var subCategory: SubCategory = SubCategory() subCategory.subCategoryId = subCategoryObj.valueForKey(WSConstants.SUBCATEGORY_ID) as Int subCategory.subCategoryName = subCategoryObj.valueForKey(WSConstants.NAME) as String subCategory.subCategoryType = subCategoryObj.valueForKey(WSConstants.SUBCATEGORY_TYPE) as Int subCategoryList.append(subCategory) } self.catAndSubCatDict.setValue(category, forkey: subCategoryList) // Also, I have to achieve this } 

Thank you for your responses,

Best wishes

+6
source share
1 answer

NSDictionary does not support generics, so you cannot declare this path - if you want to use it, create it like this:

 var catAndSubCatDict: NSDictionary = NSDictionary() 

Swift offers a new type of dictionary that supports generics, and to create it you just need to replace NSDictionary with Dictionary in your code:

 var catAndSubCatDict: Dictionary<Category, Array<SubCategory>> = Dictionary<Category, Array<SubCategory>>() 

or use one of these compact forms:

 var catAndSubCatDict: [Category : Array<SubCategory>] = [Category : Array<SubCategory>]() var catAndSubCatDict: [Category : [SubCategory]] = [Category : [SubCategory]]() 

Note that in all the cases mentioned above, you can use type inference and shorten the code by deleting the variable type:

 var catAndSubCatDict = NSDictionary() var catAndSubCatDict = Dictionary<Category, Array<SubCategory>>() var catAndSubCatDict = [Category : Array<SubCategory>]() var catAndSubCatDict = [Category : [SubCategory]]() 

Finally, with quick dictionaries you can use the class as a key - you need to make a key class ( Category in your code) to implement Hashable and Equatable protocols

+13
source

Source: https://habr.com/ru/post/975796/


All Articles