Brian
Brian

Reputation: 11

Swift: Appending to Dictionary

I am stuck with an issue with trying to append a Dictionary in swift. I am trying to log every time a button is pressed, along with the time. I have two buttons, each with their own IBAction, here's the 1st:

@IBAction func button1(sender: AnyObject){
logButton("button1")
}

In this example, I have "button1" passed to a function. Here are is my Dictionary and function:

var buttonPresses = Dictionary<String, AnyObject>()
var time = NSDate()

func logButton(button: String){
time = NSDate()
formatter.timeStyle = .shortStyle
buttonPresses[button] = formatter.stringFromDate(time)
}

After pressing both buttons, this fills the Dictionary with:

[button1: 1:15PM, button2: 1:15PM]

What I'd like to do is have it add to this each time, instead of using the key (button1 or 2) and updating the time. Preferred output is:

[button1: 1:15PM, button2: 1:15PM, button1: 1:17PM, button2: 1:19PM]

With that, I have tried making the dictionary an array containing a dictionary, so that I can use append to add each button press:

var buttonPresses = [[String:AnyObject]]()

I am not sure how to set up the line of code in the logButton function to append the button pressed with the time. I've tried something like this but it hasn't worked:

buttonPresses.append([button] = formatter.stringFromDate(time))

I'm pretty amateur, so any help would be appreciated! Thank you.

Upvotes: 1

Views: 889

Answers (2)

Eric Aya
Eric Aya

Reputation: 70098

A struct is an interesting choice to store your data with meaningful accessors:

import Cocoa

struct ButtonPress {
    var name: String?
    var time: NSDate?
    init(name: String, time: NSDate) {
        self.name = name
        self.time = time
    }
}

var buttonPresses = [ButtonPress]()

func logButton(buttonName: String) {
    let thisPress = ButtonPress(name: buttonName, time: NSDate())
    buttonPresses.append(thisPress)
}

logButton("button1")
logButton("button2")
logButton("button3")

for pressed in buttonPresses {
    println("Name: \(pressed.name!) - Time: \(pressed.time!)")
}

enter image description here

Upvotes: 2

Anthony Kong
Anthony Kong

Reputation: 40624

Dictionary is probably not the right data structure for your problem here.

From what I understand, you want to store a sequence of time associate with each buttons.

Due to the nature of dictionary, you can only store one time data per each key if you use the button label as the key *

Besides, because a dictionary is a essentially a hashtable, you will not have a nice ordered sequence of [button1: 1:15PM, button2: 1:15PM, button1: 1:17PM, button2: 1:19PM]

I would suggest you can use an array of tuple to store this information. For example,

var buttonPresses = [(code:String, time:AnyObject)]
buttonPresses.append(code:"button1", time:"1:15PM")

* It can be overcome if you store an array per key

Upvotes: 0

Related Questions