简体   繁体   English

如何从Swift 2.1中的对象数组创建字典?

[英]How do I create a dictionary from an array of objects in swift 2.1?

I have an array of type "drugList", and they are derived from a struct "DrugsLibrary": 我有一个类型为“ drugList”的数组,它们是从结构“ DrugsLibrary”派生的:

struct DrugsLibrary {
    var drugName = ""
    var drugCategory = ""
    var drugSubCategory = ""
}

 var drugList = [DrugsLibrary]()
 //This is the dictionary i'm trying to build:
 var dictionary = ["": [""," "]]

My data model is initialized using this function: 我的数据模型使用以下函数初始化:

  func createDrugsList() {        
        var drug1 = DrugsLibrary()
        drug1.drugName = "drug1"
        drug1.drugCategory = "Antibiotics"
        drug1.drugSubCategory = "Penicillins"
        self.drugList.append(drug1)  

        var drug2 = DrugsLibrary()
        drug2.drugName = "drug2"
        drug2.drugCategory = "Antibiotics"
        drug2.drugSubCategory = "Penicillins"
        self.drugList.append(drug2) 

        var drug3 = DrugsLibrary()
        drug3.drugName = "drug2"
        drug3.drugCategory = "Antibiotics"
        drug3.drugSubCategory = "Macrolides"
        self.drugList.append(drug3) 
}

my problem is that i'm trying to create a dictionary from the drugList where the key is the drugSubCategory and the value is the drug name. 我的问题是我正在尝试从drugList创建一个字典,其中的键是drugSubCategory,值是药物名称。 The value should be an array if there are several drugs in this subcategory for example, the dictionary should look something like this for this example: 例如,如果此子类别中有几种药物,则该值应为一个数组,此示例中的字典应如下所示:

 dictionary = [
     "Penicillins": ["drug1","drug2"]
     "Macrolides": ["drug3"]
    ] 

I tried this method: 我尝试了这种方法:

   for item in drugList {
        dictionary["\(item.drugSubCategory)"] = ["\(item.drugName)"]            
    }

this gave a dictionary like this, and it couldn't append drug2 to "Penicllins": 这给出了这样的字典,并且无法将drug2附加到“ Penicllins”上:

 dictionary = [
     "Penicillins": ["drug1"]
     "Macrolides": ["drug3"]
    ] 

So I tried to append the items into the dictionary using this method but it didn't append anything because there were no common items with the key "" in the data model: 因此,我尝试使用此方法将项目追加到字典中,但未追加任何内容,因为在数据模型中不存在带有键""常见项目:

for item in drugList {
  names1[item1.drugSubCategory]?.append(item1.drugName)  
  }

Anyone knows a way to append drug2 to the dictionary? 有人知道将Drug2附加到字典的方法吗?

I would appreciate any help or suggestion in this matter. 在此问题上的任何帮助或建议,我将不胜感激。

You need to create a new array containing the contents of the previous array plus the new item or a new array plus the new item, and assign this to your dictionary: 您需要创建一个新数组,其中包含前一个数组的内容加上新项或一个新数组加上新项,并将其分配给字典:

for item in drugList {
    dictionary[item.drugSubCategory] = dictionary[item.drugSubCategory] ?? [] + [item.drugName]
}

Copy this in your Playground, might help you understand the Dictionaries better: 将其复制到您的Playground中,可能有助于您更好地理解字典:

 import UIKit

var str = "Hello, playground"


struct DrugsLibrary {
    var drugName = ""
    var drugCategory = ""
    var drugSubCategory = ""
}

var drugList = [DrugsLibrary]()
//This is the dictionary i'm trying to build:
var dictionary = ["":""]

func createDrugsList() {
    var drug1 = DrugsLibrary()
    drug1.drugName = "drug1"
    drug1.drugCategory = "Antibiotics"
    drug1.drugSubCategory = "Penicillins"
    drugList.append(drug1)

    var drug2 = DrugsLibrary()
    drug2.drugName = "drug2"
    drug2.drugCategory = "Antibiotics"
    drug2.drugSubCategory = "Penicillins"
    drugList.append(drug2)

    var drug3 = DrugsLibrary()
    drug3.drugName = "drug2"
    drug3.drugCategory = "Antibiotics"
    drug3.drugSubCategory = "Macrolides"
    drugList.append(drug3)
}

createDrugsList()
print(drugList)


func addItemsToDict() {
for i in drugList {

    dictionary["item \(i.drugSubCategory)"] = "\(i.drugName)"

}
}
addItemsToDict()

print(dictionary)

You can use .map and .filter and Set to your advantage here. 您可以在此处使用.map.filterSet为您的优势。 First you want an array of dictionary keys, but no duplicates (so use a set) 首先,您需要一个字典键数组,但没有重复项(因此请使用一组)

let categories = Set(drugList.map{$0.drugSubCategory})

Then you want to iterate over the unique categories and find every drug in that category and extract its name: 然后,您要遍历唯一的类别并找到该类别中的每种药物并提取其名称:

for category in categories {
    let filteredByCategory = drugList.filter {$0.drugSubCategory == category}
    let extractDrugNames = filteredByCategory.map{$0.drugName}
    dictionary[category] = extractDrugNames
}

Removing the for loop, if more Swifty-ness is desired, is left as an exercise to the reader ;). 如果需要更多的快速性,请删除for循环,这是读者的一项练习;)。

I have two unrelated observations: 我有两个不相关的观察:

1) Not sure if you meant it as an example or not, but you've initialized dictionary with empty strings. 1)不确定您是否要举例说明,但您已使用空字符串初始化了dictionary You'll have to remove those in the future unless you want an empty strings entry. 除非您希望输入一个空字符串,否则您将来必须删除它们。 You're better off initializing an empty dictionary with the correct types: 最好用正确的类型初始化一个空字典:

var dictionary = [String:[String]]()

2) You don't need to use self. 2)您不需要使用self. to access an instance variable. 访问实例变量。 Your code is simple enough that it's very obvious what the scope of dictionary is (see this great writeup on self from a Programmers's stack exchange post. 您的代码很简单,因此很明显dictionary的范围是什么(请参阅程序员的堆栈交换博文中关于self精彩文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 SwiftUI (SWIFT) 中创建对象数组作为环境 object - How do I create an array of objects as an environment object in SwiftUI (SWIFT) Swift - 如何从具有String属性的对象数组创建字符串? - Swift - How do I create a string from array of objects that have String property? 如何使用SwiftyJSON(在Swift中)基于JSON对象数组创建对象数组? - How do I create an array of objects based on array of JSON objects using SwiftyJSON (in Swift)? 如何从元组数组创建字典? - How do I create dictionary from array of tuples? 我如何创建一个plist,可以在我的数组->字典->字典->数组-> mYClassInstances的应用程序中快速访问? - How do i create a plist that I can access nicely in my app of array -> dictionary -> dictionary -> array -> mYClassInstances in swift? 在 Swift 5 中从数组创建字典 - Create Dictionary from Array in Swift 5 如何在Swift iOS中从Dictionary中保存和检索对象数组值? - How to save and retrieve Array of Objects value from Dictionary in Swift iOS? 从swift 2中的对象和键数组创建字典 - create dictionary from objects and keys arrays in swift 2 如何根据Swift中的数组内容对字典数组进行排序 - How do I sort an array of dictionary according to an array contents in Swift 如何在Swift中访问存储在Dictionary中的数组? - How do I access an Array stored in a Dictionary in Swift?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM