How do I create a dictionary from an array of objects in swift 2.1? - ios

I have an array of type "drugList", and they are derived from a struct "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. 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":
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?
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]
}

You can use .map and .filter and Set to your advantage here. 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 ;).
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. 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. 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.

Copy this in your Playground, might help you understand the Dictionaries better:
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)

Related

create a dictonary with for loop in swift

I just want to create a dictionary with the help of for loop
sample code :
var counter: Int = 1;
var pageCountDict = [String:Any]();
for filterCount in counter..<6
{
if let count = "page_\(filterCount)_vtime" as? String
{
pageCountDict = [count: timeInterval_Int];
}
}
print(pageCountDict);
This print command give me only last value of forloop
I just want all the value of this variable pageCountDict in a dictonary
The way to assign to a dictionary is first use the subscript and assign the value to it:
pageCountDict[YourKey] = YourValue
Also, you can see many examples and explanations in Apple documentation regarding dictionaries.
With each loop, you are replacing the dictionary with one that contains only one element. What you want to do is this :
pageCountDict[count] = timeInterval_Int
Also, you shouldn't need the as? String part. This should be sufficient :
for filterCount in counter..<6
{
pageCountDict[count] = "page_\(filterCount)_vtime"
}
var pageCountDict = [String:Any]()
You can add values to this dictionary by merging previous contents and new data as follows...
let counter: Int = 1
var pageCountDict = [String:Any]()
for filterCount in counter..<6
{
let value = 9
let count = "page_\(filterCount)_vtime" //'if' is not needed as it is always true
pageCountDict.merge([count: timeInterval_Int], uniquingKeysWith:{ (key, value) -> Any in
//assign value for similar key
timeInterval_Int
})
}
print(pageCountDict)`

How to sort by comparing with each characters in swift?

Sorry, I have a question about sort data.
I don't know how to sort each characters , I just sort by first characters like following image.
How can I sort characters in each section array.
Thanks.
var cityCollation: UILocalizedIndexedCollation? = nil
var sectionsCityArray = [[City]]()
var cityArray:[City] = [City]() //cityArray is my original data that is not sorting
func configureSectionCity() {
cityCollation = UILocalizedIndexedCollation.current()
let sectionTitlesCount = cityCollation!.sectionTitles.count
var newSectionsArray = [[City]]()
for _ in 0..<sectionTitlesCount {
let array = [City]()
newSectionsArray.append(array)
}
for bean in cityArray {
let sectionNumber = cityCollation?.section(for: bean, collationStringSelector: #selector(getter: City.name))
var sectionBeans = newSectionsArray[sectionNumber!]
sectionBeans.append(bean)
newSectionsArray[sectionNumber!] = sectionBeans
}
sectionsCityArray = newSectionsArray
}
Assuming the City object has a name property and you want the order q001, q002, q004, q005, q010, q012 you could use
newSectionsArray[sectionNumber!] = sectionBeans.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
localizedStandardCompare requires the Foundation framework

How can I get the value of dict for the set of values in an array in Swift 2.0?

I am not sure I framed the question correctly. But this is the explanation: I have a dictionary of contacts:
var arrOfDictContacts = NSMutableArray()
self.arrOfDictContacts.addObject(["\(names)":"\(numb)"])
After appending
arrOfDictContacts = ["Arun":"+123", "Babu":"+234", "Chitra":"+345"]
I have an array of names arrOfNames = ["Arun", "Chitra"]
Now I want the respective number of those names from dict in an array like this:
arrOfNumbers = ["+123", "+345"] // Expected Output
How can I fetch them?
You can do it like this:
var arrOfDictContacts = Dictionary<String, String>()
arrOfDictContacts = ["Arun":"+123", "Babu":"+234", "Chitra":"+345"]
var arrOfNames = ["Arun", "Chitra"]
var arrOfContacts = [String]()
for name in arrOfNames {
arrOfContacts.append(arrOfDictContacts[name]!)
}
println("\(arrOfContacts)")
Here you go...
let arrOfDictContacts = ["Arun":"+123", "Babu":"+234", "Chitra":"+345"]
let arrOfNames = ["Arun", "Chitra"]
var arrOfNumbers = [String]()
for name in arrOfNames {
if let aNumber = arrOfDictContacts[name] {
arrOfNumbers.append(aNumber);
}
}
This one is a one-liner:
arrOfNames.map({ arrOfDictContacts[$0] })
Please try this:
let dict = ["Arun":"+123", "Babu":"+234", "Chitra":"+345"]
let names = ["Arun", "Babu"]
let allValues = dict.map({ $1 })
let valuesByName = names.map({ dict[$0] })
print("\(allValues)")
print("\(valuesByName)")
Here is how the output will look like in playground:
I think you'd better learn more about map, filter, ... in Swift. If the language provides the elegant way to do something, make sure that you utilize it instead of reinventing the wheel.

Swift: How to add dictionary arrays to an array?

Can I add dictionary arrays (is this the correct term for a dictionary key holding multiple values?) to an array?
var dictionary = [String: [String]]()
var array = [String]()
var data1:String = "55a"
var data2:String = "95a"
var data3:String = "66"
var data4:String = "25"
var data5:String = "88b"
var data6:String = "#"
dictionary["3"] = [data1, data2, data3, data4, data5, data6]
var data7:String = "#"
var data8:String = "#"
var data9:String = "#"
var data10:String = "#"
var data11:String = "#"
var data12:String = "#"
dictionary["2"] = [data7, data8, data9, data10, data11, data12]
var data13:String = "100"
var data14:String = "101"
var data15:String = "102"
var data16:String = "103"
var data17:String = "104"
var data18:String = "105"
dictionary["1"] = [data13, data14, data15, data16, data17, data18]
I tried this:
array.extend([dictionary["1"], dictionary["2"], dictionary["3"]])
but there was an error "Cannot invoke 'extend' with an argument list of type '([[(String)?])"..
How do I add dictionary["1"], ["2"] & ["3"] accordingly into the array?
Your array type declaration is not correct. Please try below one
var array: [[String:[String]] = []
In case you are not interested in the order you might try:
array.extend(flatMap(dictionary.values, {$0}))
If order is important you might build your optionalArrays first:
let optionalArrays = [dictionary["1"], dictionary["2"], dictionary["3"]]
array.extend(flatMap(optionalArrays, {$0 ?? []}))
i.e. your dictionary returns an optional array, this causes the error you reported.
Hope this helps
If you wanted an array of arrays of Strings, you need to change your array's type to be [[String]], as the other answers said.
But, when getting values out of your dictionary, you shouldn't force unwrap! It may work for this example, but in the future you'll likely get into trouble with:
'fatal error: unexpectedly found nil while unwrapping an Optional
value'
You should check to see if a value exists in the dictionary for that key, using optional binding for example:
if let value = dictionary["1"] {
array.append(value)
}
// ...
Or, you could get all the values from your dictionary into an array like so:
let array = Array(dictionary.values)
If you actually did want an array of Strings, you could use flatMap:
let array = flatMap(dictionary.values) { $0 }
Your array variable must be an Array of Array with String elements.
Also don't forget to unwrap the values of the dictionaries by adding !.
Try this:
var dictionary = [String: [String]]()
var array = [[String]]()
var data1:String = "55a"
var data2:String = "95a"
var data3:String = "66"
var data4:String = "25"
var data5:String = "88b"
var data6:String = "#"
dictionary["3"] = [data1, data2, data3, data4, data5, data6]
var data7:String = "#"
var data8:String = "#"
var data9:String = "#"
var data10:String = "#"
var data11:String = "#"
var data12:String = "#"
dictionary["2"] = [data7, data8, data9, data10, data11, data12]
var data13:String = "100"
var data14:String = "101"
var data15:String = "102"
var data16:String = "103"
var data17:String = "104"
var data18:String = "105"
dictionary["1"] = [data13, data14, data15, data16, data17, data18]
array.extend([dictionary["1"]!, dictionary["2"]!, dictionary["3"]!])
Dictionary values are returned as optionals (thus indicating if a value exists for a key) so use the '!' to unwrap the values of each dictionary array (i.e. [dictionary["1"]!)
And as suggested in other answers change your array type as it currently defined as arrays of string rather then an array of dictionaries.

Create Dictionary<String, [SomeStruct]> from [SomeStruct] source-array

var sourceEntries: [Entry] = [entry1, ..., entry14]
var myDict: Dictionary<String, [Entry]> = [:]
for entry in sourceEntries {
if var array = myDict[entry.attribute1] { theArray.append(entry) }
else { myDict[entry.attribute1] = [entry] }
}
I am intending to create a Dictionary, which matches all the objects of the struct "Eintrag" with the same attribute from the source-Array "alleEinträge" to a String containing the value of the shared attribute. For some reason my final Dictionary just matches Arrays of one element to the Strings, although some Arrays ought to contain up to four elements.
The problem is that the array is passed by value (i.e. "copied"), so the array you are writing to when you say array.append is not the array that is "inside" the dictionary. You have to write back into the dictionary explicitly if you want to change what's in it.
Try it in a simple situation:
var dict = ["entry":[0,1,2]]
// your code
if var array = dict["entry"] { array.append(4) }
// so what happened?
println(dict) // [entry: [0, 1, 2]]
As you can see, the "4" never got into the dictionary.
You have to write back into the dictionary explicitly:
if var array = dict["entry"] { array.append(4); dict["entry"] = array }
FURTHER THOUGHTS: You got me thinking about whether there might be a more elegant way to do what you're trying to do. I'm not sure whether you will think this is "more elegant", but perhaps it has some appeal.
I will start by setting up a struct (like your Entry) with a name attribute:
struct Thing : Printable {
var name : String
var age : Int
var description : String {
return "{\(self.name), \(self.age)}"
}
}
Now I will create an array like your sourceEntries array, where some of the structs share the same name (like your shared attribute attribute1):
let t1 = Thing(name: "Jack", age: 40)
let t2 = Thing(name: "Jill", age: 38)
let t3 = Thing(name: "Jill", age: 37)
let arr = [t1,t2,t3]
And of course I will prepare the empty dictionary, like your myDict, which I call d:
var d = [String : [Thing]]()
Now I will create the dictionary! The idea is to use map and filter together to do all the work of creating key-value pairs, and then we just build the dictionary from those pairs:
let pairs : [(String, [Thing])] = arr.map {
t in (t.name, arr.filter{$0.name == t.name})
}
for pair in pairs { d[pair.0] = pair.1 }

Resources