Swift:附加到字典 [英] Swift: Appending to Dictionary

查看:29
本文介绍了Swift:附加到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试快速附加字典时遇到了问题.每次按下按钮时,我都会尝试记录时间以及时间.我有两个按钮,每个按钮都有自己的 IBAction,这是第一个:

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

在这个例子中,我将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]

我想做的是每次都将它添加到此,而不是使用键(按钮 1 或 2)并更新时间.首选输出是:

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]

有了这个,我尝试使字典成为一个包含字典的数组,以便我可以使用 append 添加每个按钮按下:

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]]()

我不确定如何在 logBu​​tton 函数中设置代码行以附加按下时间的按钮.我试过这样的事情,但没有奏效:

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.

推荐答案

struct 是使用有意义的访问器存储数据的有趣选择:

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

这篇关于Swift:附加到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆