adman
adman

Reputation: 408

Swift multiple value dictionary

I'm trying to figure out how to make a grid of information in Swift. In order to do that, I'm going to need to make a variable that is somewhat like this:

var allInformationByDate = [(2016-08-13, 21, 82, 75.75, 38.34),(2016-08-12, 23, 85, 75.25, 38.34),(2016-08-11, 23, 85, 75.25, 38.34)]

It's important that I can add dates with their corresponding numbers as days go by, as well as reference a day's numbers by their date.

Does anybody know how to do this? Thanks a lot in advance.

Upvotes: 2

Views: 2172

Answers (2)

idmean
idmean

Reputation: 14865

I think dictionaries only have 2 variables per entry (a word and a definition), but I would need a few more variables recorded per entry.

That’s only partly correct. A dictionary maps keys to values. But a value is not limited to one integer. A value can very well be a class instance, a struct instance, an enum instance or a tuple/triple/etc.

So you could simply do:

let allInformationByDate = ["2016-08-13": (21, 82, 75.75, 38.34), "2016-08-12": (23, 85, 75.25, 38.34), "2016-08-11": (23, 85, 75.25, 38.34)]

But that’s nasty. You should better create a data structure to represent that data:

struct DayData { // Let’s guess
    let coffeeInLiters: Int
    let interstateRoute: Int
    let averageBPM: Double
    let temperatureInDegrees: Double
}

var allInformationByDate = [
    "2016-08-13": DayData(coffeeInLiters: 21, interstateRoute: 82, averageBPM: 75.75, temperatureInDegrees: 38.34),
    "2016-08-12": DayData(coffeeInLiters: 23, interstateRoute: 85, averageBPM: 75.25, temperatureInDegrees: 38.34),
    "2016-08-11": DayData(coffeeInLiters: 23, interstateRoute: 85, averageBPM: 75.25, temperatureInDegrees: 38.34)
]

Then you can access your data like:

allInformationByDate["2016-08-13"]!.averageBPM

and you could add data like

allInformationByDate["2016-08-14"] = DayData(coffeeInLiters: 25, interstateRoute: 87, averageBPM: 75.15, temperatureInDegrees: 38.34)

If you made coffeeInLiters a var, you could also update that variable, e.g.:

allInformationByDate["2016-08-14"]!.coffeeInLiters = 27

Upvotes: 4

Harsh
Harsh

Reputation: 2908

You can make an array of dictionaries and then access them as follows (i have created random keys like value1, value2 and more, you can make what suits you the best and then use them however you want):

var allInformationByDate:[[String:AnyObject]] = [["date":"2016-08-13","value1": 21, "value2": 82, "value3": 75.75, "value4":38.34],["date":"2016-08-13","value1": 21, "value2": 82, "value3": 75.75, "value4":38.34],["date":"2016-08-13","value1": 21, "value2": 82, "value3": 75.75, "value4":38.34]]

print(allInformationByDate.first!["date"])
print(allInformationByDate.first!["value1"])

Appending more dictionaries to the array:

allInformationByDate.append(["date":"2016-08-13","value1": 21, "value2": 82, "value3": 75.75, "value4":38.34])

Upvotes: 0

Related Questions