Tuples in Property List Swift - 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

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)

Realm Swift - Convert an array of results into an array of Ints

I want to convert the results from my Realm data into Int.
Here is an example of how I want to use this.
let results = realm.objects(Data.self)
print(results)
However the result is type Results<Data> and cannot be converted into a Int but the results is an Int.
Just to be clear I want an array of Int from my results
You can simply use Array(realm.objects(RealmType.self)), which will convert the Results<RealmType> instance into an Array<RealmType>.
However, there are other serious flaws with your code. First of all, neither of the last two lines will compile, since firstly realm.objects() accepts a generic input argument of type Object.Type and Data doesn't inherit from Object. You can't directly store Data objects in Realm, you can only store Data as a property of a Realm Object subclass.
Secondly, myArray[results] is simply wrong, since results is supposed to be of type Results<RealmType>, which is a collection, so using it to index an Array cannot work (especially whose Element type is different).
It appears that based on the number of results from the database, you want to select an object from the array.
You can get the number of items in an array with .count. Be certain that an object exists at the specified index in the array, or your application will crash!
let numberOfResults = results.count
if myArray.count > numberOfResults {
let object = myArray[numberOfResults]
print(object)
}

how to add multiple key value pairs to dictionary 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!)

Create a mutable array of arrays each containing a dictionary in swift?

I am trying to declare a variable that stores an array of arrays. Each array then contains a Dictionary object. I tried a bunch of different possible declarations but the compiler is not happy with any of them.
Any suggestion?
Thanks
Clarification on what I needed:
An array that contains arrays where each of them contains dictionaries.
You Said
Each array then contains a Dictionary object
that mean that each array will have a single Dictionary so why do you need that extra Array
anyway the following code declare an Array that contain Dictionaries(The code assume that eventually your dictionary will contain strings but you can change that to any type you want)
var myObj = Array<Dictionary<String,String>>()
var dic1:Dictionary<String,String> = Dictionary<String,String>()
dic1["A"] = "Alpha :A"
dic1["B"] = "Alpha :B"
var dic2:Dictionary<String,String> = Dictionary<String,String>()
dic2["C"] = "Alpha :C"
dic2["D"] = "Alpha :D"
myObj.append(dic1)
myObj.append(dic2)
if you need an array containing arrays of dictionaries it will be almost the same
var myObj = Array<Array<Dictionary<String,String>>>()