Swift:追加字典 [英] Swift: Appending to Dictionary

查看:1217
本文介绍了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]

我想做的是每次都添加它,而不是使用键(button1或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天全站免登陆