how to add multiple key value pairs to dictionary Swift - swift

okay, i'm trying to have the user add a key and value pair to a dictionary i created and have it show up in a table view. i do that just fine but i cant seem to figure out how to add another pair. when i go to add another it replaces the last one. id really like to have multiple pairs. can someone help please?
heres my code:
//declaring the dictionary
var cart = [String:String]()
//attempting to add to dictionary
cart[pizzaNameLabel.text!] = formatter.stringFromNumber(total)

This is how dictionary works:
In computer science, an associative array, map, symbol table, or
dictionary is an abstract data type composed of a collection of (key,
value) pairs, such that each possible key appears at most once in the
collection.
So
var cart = [String:String]()
cart["key"] = "one"
cart["key"] = "two"
print(cart)
will print only "key" - "two" part. It seems that you may need an array of tuples instead:
var cart = [(String, String)]()
cart.append(("key", "one"))
cart.append(("key", "two"))
print(cart)
will print both pairs.

From Swift 5.0, you can use KeyValuePairs like ordered dictionary type with multiple keys.
See this Apple Document of KeyValuePairs. ;)
let recordTimes: KeyValuePairs = ["Florence Griffith-Joyner": 10.49,
"Evelyn Ashford": 10.76,
"Evelyn Ashford": 10.79,
"Marlies Gohr": 10.81]
print(recordTimes.first!)

Related

swift Dictionary problem where it needs to be ordered by the key

I have an issue where I am able to sort the dictionary however the result is weird.
class MyModel {
var dict = [Date: Int]()
...
}
let sortDict = dict.sorted { (first, second) -> Bool in
return first.key > second.key
}
dictDatePlacesCount = sortDict[0]
The issue is that I get a syntax error
Cannot assign value of type 'Dictionary<Date, Int>.Element' (aka '(key: Date, value: Int)') to type '[Date : Int]'
The question is that I cannot create a custom Dictionary with this rule of sorting in descending order with the Date?
I did explore and found OrderedDictionary but it seems like an external package?
As jnpdx says, the Dictionary method sorted() returns an array of tuples of type (Key, Value) (So (Date, Int) in your case.)
The Swift standard library doesn't have an ordered dictionary. Again, as mentioned by jnpx, there are frameworks/libraries like the official Swift Collections that offer ordered dictionaries. You might want to use one of those.
Alternatively, you could sort the keys from your dictionary and use those to index into your contents.

Convert Realm list of Strings to Array of Strings in Swift

I'm just starting up with RealmSwift, and I'm trying to store an array of Strings in Realm. It doesn't work, so now I'm using List<String>() as an alternative. However, how do I convert these Realm Lists back to [String] again? And if I can't do that, are there any alternatives?
Thanks
However, how do I convert these Realm Lists back to [String] again
You can simply cast List to Array, because List has Sequence Support:
let list = List<String>()
let array = Array(list)
Bear in mind that by converting to an array you'll lose the 'dynamic' quality of a Realm collection (i.e. you'll receive a static array, whereas keeping the original List will provide automatic updating should the source change). But you can create an array by using an extension, e.g.:-
extension RealmCollection
{
func toArray<T>() ->[T]
{
return self.compactMap{$0 as? T}
}
}
Then use:-
let stringList = object.strings.toArray()
Where object is the realm object, and strings is your field.
Here are the details. how to assign an array in the realm list model.
jim.dogs.append(objectsIn: someDogs)

Getting Key from Dict as String in Swift

New to coding here.
I have a dict with strings as keys and arrays of integers as values and I'm trying to get, from a given key, the String of that key. Not the value of the key, but the key itself. Now, I would just put an extra String into the array and call that, but my Xcode seems to have a bug where it really doesn't like having mixed type arrays and it doesn't work.
An example looks like this:
var allDict: [String: [Int]] = [:];
allDict.updateValue([1, 2, 3], forKey: "BAGEL"]);
allDict.updateValue([4, 5, 6], forKey: "DONUT"]);
allDict.updateValue([7, 8, 9], forKey: "MACARON"]);
I can get the values of each array quite fine with allDict["DONUT"]![1] //prints 5 for example, but what I want is to get the String of the key.
i.e. I would like to print DONUT using allDict["DONUT"]!
Is this possible? Thank you in advance!
It looks like you know your keys going in, in this example.
Here are a few ways you might recover your keys in a useful way, though:
Say you have a dictionary
var dict: [String: Int] = ...
You could get the array of keys:
let keys = dict.keys // keys is of type [String]
You can iterate over keys and values:
for (key, value) in dict {
...
}
You can merge dictionaries of and choose values from either dictionary when keys collide:
let mergedDict = dict.merge(otherDict) { leftValue, rightValue in
return leftValue
}
Addressing a version of your original question briefly:
Say you have the value for a certain key:
let donutValue = dict["DONUT"]
and somewhere else, where you lo longer have access to the key, you want to recover it from the value somehow. The best you could do is attempt to find the key by searching through the dictionary with the value you have.
var searchResult = dict.first { key, value in
return value == donutValue
}
This assumes the values in your dictionary are Equatable. Otherwise, you have to write some function or logic to figure out whether or not you've found that value in the dictionary corresponding to donutValue.

Create a dictionary in a loop in Swift

I have a variable set of objects that I need to place in a dictionary. I'm trying to add them to the dictionary in a for loop but from what I'm understanding dictionaries are immutable so they need to be declared immediately. How do I create a dictionary list of items that are not predetermined?
var newItems = [:]
for item in self.items{
newItems["\(item.key)"]["name"] = "A new item"
}
does not use the second value
var newItems : [String:String] = [:]
for i in 1..10{
newItems[i.description] = "A new item"
}
for more information https://www.weheartswift.com/dictionaries/
The problem with your original code is that dictionaries only have one key, so this construct newItems["\(item.key)"]["name"] is syntactically incorrect. If you had a fixed number of properties you could use a struct and put that in a dictionary. As you posed the question, though, you need to create a dictionary where the stored elements themselves are dictionaries. So, although I didn't actually put this into Xcode, it's a template for what you need to do:
var newItems = [:[:]]()
for item in self.items {
var itemDict = [:]()
for prop in whereeveryourpropertiescomefrom {
itemDict[prop] = valueforthisproperty
}
newItems["\(item.key)"] = itemDict
}
Of course, if your properties were initially stored in a dictionary unique to this item (equivalent of the inner loop), just store it directly into newItems.
Then, you could reference things as
let value = newItems["\(item.key)"]?.["property key"]
Notice the dictionary retrieval returns an optional you have to deal with.
The solution was when initializing the dictionary to create another dictionary
var newItems: [String:[String:AnyObject]]()

Tuples in Property List Swift

I want to create a property list to build up a graph using adjacent list representation.
So in the property list, I want to have a dictionary ([String: Array]). The string will be the node, the array will store its neighbors.
Inside the Array, I would like to have (String, Int) tuples, the String for the neighbor, the Int for the weight (each tuple represents an edge incident to the node).
The problem is that I cannot have tuples inside Property List. I could use Dictionary, but it seems an array of dictionary with only one item inside that dictionary is not worth it. Any better solutions? Thanks!
How about this
let node = "node"
let incident = ( "edge1", 12 )
var dictionary:[String:Array<Any>] = [:]
dictionary[node] = [ incident.0, incident.1 ]
This should give you a dictionary with a string and an array from your tuples