Swift equivalent of NSDictionary with objects and keys?

I want to have a dictionary that contains multiple value for keys per entry so I can iterate through all dictionary entries and retrieve those values for each entry.


I want to learn how to do it in this format.


var newDict = [String:CGPoint]()


But I want it to have multiple values for multiple keys. For example, to retain values for certain entries such as IDNumber (String), ItemType (String or Int), TimeSinceInitialized(Int for seconds).


That way I can do something like this.


for entry in newDict{

     entry.valueForKey("IDNumber") == ??
     entry.valueForKey("ItemType" == ??
     entry.valueForKey("TimeSinceInit") == ??
}


Is it possible to store all these values for each object in a dictionary rather than use a class?

Answered by ahaese in 72368022

Two possibilities:


First, nested dictionaries:

var data = [String: [String: AnyObject]]()
data["item1"] = ["IDNumber": 123, "ItemType": "Unicorn", "TimeSinceInit": 60]

Now you can iterate over your main dictionary and then iterate over the individual sub dictionaries

for (key, subDict) in data {
   for (dataKey, value) in subDict {
       print(dataKey, value)
   }
}


This way, your data structure is very flexible but at the same time not very homogenous (particularly, not inherently type safe). If you always want to have the same value types for each dictionary entry but don't want to use classes, I'd recommend using a struct to describe your sub data:

struct MyData {
    var idNumber: String
    var itemType: String
    var timeSinceInit: Int
}

var data = [String: MyData]()


Of course you could also use enums, or arbitrarily nest any of those types. For these kinds of problems, Playgrounds is perfectly suited to play around until you find a solution that works best for you.

Accepted Answer

Two possibilities:


First, nested dictionaries:

var data = [String: [String: AnyObject]]()
data["item1"] = ["IDNumber": 123, "ItemType": "Unicorn", "TimeSinceInit": 60]

Now you can iterate over your main dictionary and then iterate over the individual sub dictionaries

for (key, subDict) in data {
   for (dataKey, value) in subDict {
       print(dataKey, value)
   }
}


This way, your data structure is very flexible but at the same time not very homogenous (particularly, not inherently type safe). If you always want to have the same value types for each dictionary entry but don't want to use classes, I'd recommend using a struct to describe your sub data:

struct MyData {
    var idNumber: String
    var itemType: String
    var timeSinceInit: Int
}

var data = [String: MyData]()


Of course you could also use enums, or arbitrarily nest any of those types. For these kinds of problems, Playgrounds is perfectly suited to play around until you find a solution that works best for you.

Swift equivalent of NSDictionary with objects and keys?
 
 
Q