Swift: Appending to Dictionary

半世苍凉 提交于 2019-12-24 16:54:25

问题


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.


回答1:


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!)")
}




回答2:


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



来源:https://stackoverflow.com/questions/29464701/swift-appending-to-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!