我试图每天从午夜开始尝试从阵列中选择一个新元素,然后一旦使用了所有元素,就跳回到数组的开头。最好的方法是什么?这是我到目前为止所拥有的。
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))
}
答案 0 :(得分:0)
要使用模运算符包围数组,它会分配index / number of items in the array
并返回除法的其余部分 - 在这种情况下始终为0...4
let wordsArray = ["Hallo","Apfel","Geburtstag","Pferd","Angst"]
for i in 0..<10 {
print(wordsArray[i % wordsArray.count])
}
在代码中创建索引变量
var index = 0
以这种方式递增
index = (index + 1) % wordsArray.count
答案 1 :(得分:0)
如果我理解你,你想每天使用某个数组元素,这些元素应该循环选择。
所以主要问题是如何在午夜每天做点什么
这可以使用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!
}
此代码尚未经过测试,但它应该让您知道如何继续。
答案 2 :(得分:-1)
这是我能想到的最简单的方法。
var wordsArray = [String] ()
wordsArray = ["Hallo","Apfel","Geburtstag","Pherd","Angst"]
let secondsInDay = (60 * 60 * 24)
let dayNumber = Int(NSDate().timeIntervalSince1970 / Double(secondsInDay))
let selectedNumber = dayNumber % wordsArray.count
let chosenWord = wordsArray[selectedNumber]
print(chosenWord)
编辑:希望满足投诉的另一种方法
var wordsArray = [String] ()
wordsArray = ["Hallo","Apfel","Geburtstag","Pherd","Angst"]
let calendar = Calendar(identifier: .gregorian)
let date = Date()
let yearNumber = calendar.component(.year, from: date)
let monthNumber = calendar.component(.month, from: date)
let dayNumber = calendar.component(.day, from: date)
let daysInYear = Double(yearNumber) * 12.0 * 365.25
let daysInMonth = Double(monthNumber) * 30.42
let totalNumber = daysInYear + daysInMonth + Double(dayNumber)
let selectedNumber = Int(totalNumber) % wordsArray.count
let chosenWord = wordsArray[selectedNumber]
print(chosenWord)