我一直在尝试使用类类型键和值来声明一个NSDictionary,如下所示:
var catandSubCatDict: NSDictionary<Category,Array<SubCategory>> = NSDictionary<Category,Array<SubCategory>>()
这里,“Category”和“SubCategory”是全局类.我知道我不能将类类型用于关键字段.但是,无论如何,我应该做到这一点.有没有办法做到这一点?如何声明专门的NSDictionary或类似的东西来做到这一点?
另外,我使用这样的字典:
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 }
谢谢您的回答,
最好的祝福
解决方法
NSDictionary不支持泛型,因此您无法声明这种方式 – 如果要使用它,请按如下方式对其进行实例化:
var catandSubCatDict: NSDictionary = NSDictionary()
Swift提供了一个新的字典类型,它支持泛型,并且要创建它,你只需要在代码中用字典替换NSDictionary:
var catandSubCatDict: Dictionary<Category,Array<SubCategory>> = Dictionary<Category,Array<SubCategory>>()
或使用以下紧凑形式之一:
var catandSubCatDict: [Category : Array<SubCategory>] = [Category : Array<SubCategory>]() var catandSubCatDict: [Category : [SubCategory]] = [Category : [SubCategory]]()
请注意,在上面提到的所有情况下,您可以使用类型推断并通过删除变量类型来缩短代码:
var catandSubCatDict = NSDictionary() var catandSubCatDict = Dictionary<Category,Array<SubCategory>>() var catandSubCatDict = [Category : Array<SubCategory>]() var catandSubCatDict = [Category : [SubCategory]]()
最后,使用swift词典,您可以使用类作为键 – 您需要做的是使密钥类(代码中的类别)实现Hashable和Equatable协议