Adding multiple values into a single key in swift? - swift

When I try to add multiple values to the key, my value gets overridden by the last value I assigned to the key. I tried adding brackets between the value String of my [String: [String]] key-value pair. I did that to hopefully achieve the effect to add multiple values into that key.
import UIKit
var parent = [String: [String]]()
parent["parent"] = ["Tommy Turner", "Wolfgang Motart"]
parent["parent"] = ["Bobby Bushe"]
print(parent)
// How can I add multiple values into the parent key like this:
// ["parent": "Tommy Turner", "Wolgang Motart", "Bobby Bushe"]

Since the type of parent["parent"] is array of string, you can use append function for adding one or multiple elements. Try this.
var parent = [String: [String]]()
parent["parent"] = ["Tommy Turner", "Wolfgang Motart"]
parent["parent"]?.append("bob") // append one element to become ["Tommy Turner", "Wolfgang Motart", "bob"]
parent["parent"]?.appendContentsOf(["hello", "world"]) // append collection
print(parent["parent"]!) // ["Tommy Turner", "Wolfgang Motart", "bob", "hello", "world"]

You should add new array to previous like:
var parent = [String: [String]]()
parent["parent"] = ["Tommy Turner", "Wolfgang Motart"]
parent["parent"] = (parent["parent"] ?? []) + ["Bobby Bushe"]
print(parent)

why not combine the [string] and assign to the key:
var parent = [String: [String]]()
let value = ["Tommy Turner", "Wolfgang Motart"] + ["Bobby Bushe"]
parent["parent"] = value
print(parent) // ["parent": ["Tommy Turner", "Wolfgang Motart", "Bobby Bushe"]]

You are overriding the key of "parent" in this key-value pairing. If you want it to have those three names, just put all three names in the array.
parent["parent"] = ["Name", "name", "nombre"]
If you were to create an array outside of scope, and set the value for "parent"
var namesArray = ["Name", "name"]
parent["parent"] = namesArray
namesArray.append("nombre")
It would still only print out ["Name", "name"]. However, if you were to call
parent["parent"] = namesArray
again, it would create what you want.

Related

appending key value pair to existing dictionary values in swift

I'm trying achieve below results. Where I can save multiple key values for multiple string items.
//dict["Setting1"] = ["key1":"val1"]
//dict["Setting1"] = ["key2":"val2"]
//dict["Setting2"] = ["key1":"val1"]
//dict["Setting2"] = ["key2":"val2"]
// and so on..
//or
//dict["Setting1"].append(["key2":"val2"]) // this doesn't work
//accessing dict["Settings1"]["key1"] ..should give me val1
var dict = [String:[String:String]]()
var lst1 = ["key2":"val2"]
dict["one"] = ["key1":"val1"]
dict["one"]?.append(lst1)
print(dict)
gives me error
error: value of type '[String : String]' has no member 'append'
obj["one"]?.append(lst1)
~~~~~~~~~~~ ^~~~~~
You're using a Dictionary which doesn't have methods like append(_:). append(:_) adds something to the end of an Array, but Dictionaries are unordered.
To add something to a Dictionary, you first define a key for it, and then assign it a value in the Dictionary
It'll look like this:
var dict = [String :[String: String]]()
var lst1 = ["key2": "val2"]
dict["one"] = ["key1": "val1"]
But you can't append to dict["one"], because it's not an array, you can only overwrite it
dict["one"] = lst1

Add two dictionary values in new array . the array values will remains unchanged from its position

Add two dictionary values in a new array. the array values will remain unchanged from its position. I need to add two dictionary values in a new array. The values added in the array must remain constant at every run.
var dictionary1:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
var dictionary2:[String:Int] = ["Surya":91, "John":79, "Saranya":92]
dictionary1.merge(dictionary2){(current, _) in current}
var arr : [String] = []
for (key, value) in dictionary1 { arr.append("(key) (value)") }
print(dictionary1)
Simply use append(contentsOf:) to add the contents of dictionary1 and dictionary2 to arr. Use map(_:) to format the key-value pairs while adding to the array.
let dictionary1 = ["Mohan":75, "Raghu":82, "John":79]
let dictionary2 = ["Surya":91, "John":79, "Saranya":92]
var arr = [String]()
arr.append(contentsOf: dictionary1.map({"\($0.key) \($0.value)"}))
arr.append(contentsOf: dictionary2.map({"\($0.key) \($0.value)"}))
print(arr) //["Mohan 75", "John 79", "Raghu 82", "Surya 91", "John 79", "Saranya 92"]
As apple stats, you can use KeyValuePairs to maintain ordered collection of key-value pairs and don’t require the fast key lookup that the Dictionary type provides.
let recordTimes: KeyValuePairs = ["Florence Griffith-Joyner": 10.49,
"Evelyn Ashford": 10.76,
"Evelyn Ashford": 10.79,
"Marlies Gohr": 10.81]
print(recordTimes.first!)
// Prints "("Florence Griffith-Joyner", 10.49)"
Check if it is helpful in your case.

Swift dictionary, a key with multiple values

I would like to know how I can make a key of a dictionary have multiple values according to the data that comes to it.
Attached basic example:
var temp = [String: String] ()
temp ["dinningRoom"] = "Table"
temp ["dinningRoom"] = "Chair"
In this case, I always return "Chair", the last one I add, and I need to return all the items that I am adding on the same key.
In this case, the "dinningRoom" key should have two items that are "Table" and "Chair".
You can use Swift Tuples for such scenarios.
//Define you tuple with some name and attribute type
typealias MutipleValue = (firstObject: String, secondObject: String)
var dictionary = [String: MutipleValue]()
dictionary["diningRoom"] = MutipleValue(firstObject: "Chair", secondObject: "Table")
var value = dictionary["diningRoom"]
value?.firstObject
You can declare a dictionary whose value is an array and this can contain the data you want, for example:
var temp = [String: [String]]()
temp["dinningRoom"] = ["Table", "Chair", "Bottle"]
If you want to add a new element you can do it this way:
if temp["dinningRoom"] != nil {
temp["dinningRoom"]!.append("Flower")
} else {
temp["dinningRoom"] = ["Flower"]
}
Now temp["dinningRoom"] contains ["Table", "Chair", "Bottle", "Flower"]
Use Dictionary like this:
var temp = [String: Any]()
temp["dinningRoom"] = ["Table", "Chair"]
If you want to fetch all the elements from dinningRoom. You can use this:
let dinningRoomArray = temp["dinningRoom"] as? [String]
for room in dinningRoomArray{
print(room)
}
It is not compiled code but I mean to say that we can use Any as value instead of String or array of String. When you cast it from Any to [String]
using as? the app can handle the nil value.

Initiate empty Swift array of dictionaries

I currently have this:
var locations = [
["location": "New York", "temp": "2 °C", "wind": "3 m/s"]
]
And I add stuff to this with locations.append(). It works great!
However, I don't want there to be a default entry. So I tried
var locations = [] // Not working.
var locations = [] as NSArray
var locations = [] as NSMutableArray
var locations = [] as NSDictionary
var locations = [] as NSMutableDictionary
var locations = [:] as ... everything
var locations = [APIData]
Feels like I've tried everything but I still get countless errors whatever I try. At this stage I'm even surprised my default locations is working.
How do I solve this? How do I make locations empty to start with?
If we assume you try to initialize a array of dictionary with key String and value String you should:
var locations: [[String: String]] = []
then you could do:
locations.append(["location": "New York", "temp": "2 °C", "wind": "3 m/s"])
To create an array or dictionary you should know the type you need.
With
var array: [String]
you declare a variable to contain an array of strings. To initialize it, you can use
var array: [String] = [String]()
You can omit the : [String] because the compiler can automatically detect the type in this case.
To create a dictionary you can do the same, but you need to define both, the key and the value type:
var dictionary = [String: String]()
Now, what you ask for is an array of dictionaries, so you need to combine both to
var arrayOfDictionaries = [[String: String]]()

Adding additional items to dictionary

Would like to add John together with Peter in this combination:
var myData0: [String: String] = ["Item": "Milk", "Description": "Milk is white", "DrinksMilk": "Peter"]
myData0["DrinksMilk"] = "John"
println(myData0)
Println gives only John back instead Peter AND John. Is there a way to add John without overwriting Peter?
If you want to keep a string value of dictionary, you can do like that
var myData0: [String: String] = ["Item": "Milk", "Description": "Milk is white", "DrinksMilk": "Peter"]
myData0["DrinksMilk"] = myData0["DrinksMilk"]! + ", John"
println(myData0)
If not, you can change the type of dictionary value to AnyObject like that :
var myData0: [String: AnyObject] = ["Item": "Milk", "Description": "Milk is white", "DrinksMilk": "Peter"]
myData0["DrinksMilk"] = [myData0["DrinksMilk"]!, "John"]
println(myData0)
It appears that you are attempting to encode a data type into a dictionary. A better approach, not knowing anything more about your specific problem, is to define a class for this:
class Drink {
var name:String
var desc:String
var drinkers:[Person]
// ...
func addDrinker (person:Person) {
drinkers.append(person)
}
}
You've declared your dictionary to hold values of type String but, as you describe, now you want the dictionary values to be String or Array. The common type of these type value types is Any (it can be AnyObject if you've imported Foundation; but that is a Swift anomaly). You will then need to 'fight' the type system to coerce the "DrinksMilk" field as a modifiable array and to add "John".
// First extract `"DrinksMilk"` and force it to a mutating array:
var drinkers:[String] = myData0["DrinksMilk"]! as [String]
// Add the new drinker
drinkers.append("John")
// Reassign back into data
myData0["DrinksMilk"] = drinkers