Ryan Powell Ryan Powell - 1 year ago 57
Swift Question

How can I print a new array element every day?

So I'm trying to loop through a new element of my array every day starting at midnight, and then once all elements have been used, jumping back to the start of the array. What would be the best way to do so? Here's what I have so far.

import UIKit

var wordsArray = [String] ()

wordsArray = ["Hallo","Apfel","Geburtstag","Pherd","Angst"]

let date = NSDate ()
let calendar:NSCalendar! = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
var dateComponents = DateComponents()
dateComponents.day = 1

while wordsArray (0..<2) {
gregorian.date(byAdding: NSCalendar.Unit.day, value: $0, to: now, options: NSCalendar.Options(rawValue: 0))

Answer Source

If I understand you right, you want to use a certain array element every day, and these elements should be chosen cyclically.
So the main problem is how to do something every day at midnight.
This can be achieved using a Timer:

// First determine coming midnight
let calendar = NSCalendar.current
let nextDay = calendar.date(byAdding: .day, value: 1, to: Date())
let comingMidnight = calendar.startOfDay(for: nextDay!)

// Then start a time coming midnight, and repeat it every day
// Please note that 24 * 60 * 60 is not completely correct considering daylight saving times
// Sometimes days have 23 hours and sometimes 25 hours!
_ = Timer.init(fireAt: comingMidnight, interval: 24 * 60 * 60, target: self, selector: Selector(("timerFired")), userInfo: nil, repeats: true)

// And this is the timer callback:
func timerFired(timer: Timer) {
    // Here you can select the next element in your array, any do what is required
    // For selecting the elements cyclically, see the other answers!

This code has not been tested, but it should give you an idea how to proceed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download