Merge all values of array in a dictionary - ios

I have a dictionary of var tags = [String:[String]](). When returning the values to the REST endpoint I need to merge all the values in [String] array. Can I do something with using
self.tags.map { $0.value }
But no clue how to get a single array using all the values arrays from dictionary.

Yes you can do that using flatMap
var tags = [String:[String]]()
tags["1"] = ["2","3"]
tags["2"] = ["4","5"]
let arr = tags.values.flatMap{$0}
OR
let arr = tags.flatMap(\.value)
Prints
print(arr) // ["2","3","4","5"]

You can use flatMap to achieve this:
var tags = [String:[String]]()
var values = tags.flatMap { $0.value }
// or using keypath
var values = tags.flatMap(\.value)
Or use flatMap on values like this:
var values = tags.values.flatMap{$0}

Related

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":
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)

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.

How to append associative array elements in Swift

How do I create and append to an associative array in Swift? I would think it should be something like the following (note that some values are strings and others are numbers):
var myArray = []
var make = "chevy"
var year = 2008
var color = "red"
myArray.append("trackMake":make,"trackYear":year,"trackColor":color)
The goal is to be able to have an array full of results where I can make a call such as:
println(myArray[0]["trackMake"]) //and get chevy
println(myArray[0]["trackColor"]) //and get red
Simply like this:
myArray.append(["trackMake":make,"trackYear":year,"trackColor":color])
Add the brackets. This will make it a hash and append that to the array.
In such cases make (extensive) use of let:
let dict = ["trackMake":make,"trackYear":year,"trackColor":color]
myArray.append(dict)
The above assumes that your myArray has been declared as
var myArray = [[String:AnyObject]]()
so the compiler knows that it will take dictionary elements.
I accept above answer.It is good.Even you have given correct answer,I like to give simplest way.The following steps are useful,if you guys follow that.Also if someone new in swift and if they go through this,they can easily understand the steps.
STEP 1 : Declare and initialize the variables
var array = Array<AnyObject>()
var dict = Dictionary<String, AnyObject>()
var make = "chevy"
var year = 2008
var color = "red"
STEP 2 : Set the Dictionary(adding keys and Values)
dict["trackMake"] = make
dict["trackYear"] = year
dict["trackColor"] = color
println("the dict is-\(dict)")
STEP 3 : Append the Dictionary to Array
array.append(dict)
println("the array is-\(array)")
STEP 4 : Get Array values to variable(create the variable for getting value)
let getMakeValue = array[0]["trackMake"]
let getYearValue = array[0]["trackYear"]
let getColorValue = array[0]["trackColor"]
println("the getMakeValue is - \(getMakeValue)")
println("the getYearValue is - \(getYearValue)")
println("the getColorVlaue is - \(getColorValue)")
STEP 5: If you want to get values to string, do the following steps
var stringMakeValue:String = getMakeValue as String
var stringYearValue:String = ("\(getYearValue as Int)")
var stringColorValue:String = getColorValue as String
println("the stringMakeValue is - \(stringMakeValue)")
println("the stringYearValue is - \(stringYearValue)")
println("the stringColorValue is - \(stringColorValue)")
STEP 6 : Finally the total output values are
the dict is-[trackMake: chevy, trackColor: red, trackYear: 2008]
the array is-[{
trackColor = red;
trackMake = chevy;
trackYear = 2008;
}]
the getMakeValue is - Optional(chevy)
the getYearValue is - Optional(2008)
the getColorVlaue is - Optional(red)
the stringMakeValue is - chevy
the stringYearValue is - 2008
the stringColorValue is - red
Thank You
This sounds like you are wanting an array of objects that represent vehicles. You can either have an array of dictionaries or an array of vehicle objects.
Likely you will want to go with an object as Swift arrays and dictionaries must be typed. So your dictionary with string keys to values of differing types would end up having the type [String : Any] and you would be stuck casting back and forth. This would make your array of type [[String : Any ]].
Using an object you would just have an array of that type. Say your vehicle object's type is named Vehicle, that would make your array of type [Vehicle] and each array access would return an instance of that type.
If I want to try it with my own statement. Which also I want to extend my array with the data in my dictionary and print just the key from dictionary:
var myArray = ["Abdurrahman","Yomna"]
var myDic: [String: Any] = [
"ahmed": 23,
"amal": 33,
"fahdad": 88]
for index in 1...3 {
let dict: [String: Any] = [
"key": "new value"
]
// get existing items, or create new array if doesn't exist
var existingItems = myDic[myArray] as? [[String: Any]] ?? [[String: Any]]()
// append the item
existingItems.append(myArray)
// replace back into `data`
myDic[myArray] = existingItems
}

How to unwrap NSMutableDictionary.allkeys in optional String Array

I am trying to get all the key values of NSMutableDictionary as String Array. I am using this myNSMutableDictionary.allkeys to get the values as an Array but I cannot find a way to unwrap the key values.
This is what I have tried so far:
for (key, _) in NSMutableDictionary {
println("THIS IS MY NEW KEY\(key)")
}
And I tried this
var myArray:NSArray = myNSMutableDictionary.allKeys
var string:NSString? = uniqueIDArray[0] as? NSString
println("This is unwraped value\(string!)")
And this
var myArray:Array = myNSMutableDictionary.allKeys
println("This is unwraped value\(myArray[0])")
I keep getting the value as Optional("kMSZgoTmiX") instead of kMSZgoTmiX which is the key value I need
Thank you for all your help!
So you've got a dictionary with values that are strings (and keys that are something, assume String):
var dictionaryOfStringValues : [String:String] = /* your dictionary */
And you want to iterate over the contents:
for (key, val) in dictionaryOfStringValues {
// use key and val
}
If you just want the values in a way you can easily iterate over:
var theValues = dictionaryOfStringValues.values
If you insist that theValues be an Array:
var theValuesAsAnArray = Array(dictionaryOfStringValues.values)
If you are starting with an NSMutableDictionary, then convert it at the point where it FIRST ENTERS your Swift code into a Swift Dictionary. Use an as variant to do that. After that, pure Swift.
Like this:
7> for (key, value) in ["a":1, "b":2] {
8. println (key)
9. println (value)
10. }
b
2
a
1
let myNSMutableDictionary = NSMutableDictionary()
myNSMutableDictionary["myKey1"] = 5
myNSMutableDictionary["myKey2"] = 10
myNSMutableDictionary["myKey3"] = 15
let myKeysArrayUnsorted = myNSMutableDictionary.allKeys as [String]
let myValuesArrayUnsorted = myNSMutableDictionary.allValues as [Int]
let keyString = myKeysArrayUnsorted[0] // "myKey2"
let keyValue = myNSMutableDictionary[keyString] as Int // 10
println("This is my first unsorted key \(keyString) = \(keyValue)")
let myKeysArraySorted = (myNSMutableDictionary.allKeys as [String]).sorted(<)
for key in myKeysArraySorted {
println(myNSMutableDictionary[key]!) // 5 10 15
}

Resources