31272

Swift: Appending to Dictionary

Question:

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.

Answer1:

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

<img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/UwitA.png" data-original="https://i.stack.imgur.com/UwitA.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" />

Answer2:

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

<em>* It can be overcome if you store an array per key</em>

Recommend

  • (Swift) Setting UIDatePicker View from User Input
  • Convert an array of times from 24hr to 12 hr in Swift
  • Finding time between dates in Swift [duplicate]
  • passed object nil into my second view
  • How to implment laps in Stop Watch iphone app
  • Did back key destroy an activity?
  • Client server multithread Socket
  • Why is signal.SIGTERM not dealt with properly in my main thread?
  • UIdatepicker showing weekdays
  • how to find the index position of the ARRAY Where NSPredicate pick the value. I use filteredArrayUsi
  • boost::format vs sprintf
  • Left and right button misbehaving when trying to add an empty span to contenteditable div
  • Cleave.js Phone CA
  • IF statement formatting best-practise, what's your style?
  • How to format data from string variable
  • Are there any libraries for Python to simulate keyboard action?
  • iOS: Detect app start via notification press
  • Deselecting radio buttons while keeping the View Model in synch
  • Javascript simulate pressing enter in input box
  • How reduce the height of an mschart by breaking up the y-axis
  • How to add date and time under each post in guestbook in google app engine
  • SSO with signing and signature validation doesn't work
  • How to show dropdown in excel using jrxml (jasper api)?
  • Importing jscolor library in angular 2
  • Release, debug version and Authorization Google?
  • Websockets service method fails during R startup
  • Alternatives to the OPTIONAL fallback SPARQL pattern?
  • How to get next/previous record number?
  • Apache 2.4 - remove | delete | uninstall
  • Compare two NSDates in iPhone
  • trying to dynamically update Highchart column chart but series undefined
  • Proper way to use connect-multiparty with express.js?
  • Trying to get generic when generic is not available
  • embed rChart in Markdown
  • How to get Windows thread pool to call class member function?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • costura.fody for a dll that references another dll
  • Observable and ngFor in Angular 2
  • UserPrincipal.Current returns apppool on IIS
  • java string with new operator and a literal