【问题标题】:SwiftUI - how to shuffle an array one time a day?SwiftUI - 如何每天洗牌一次?
【发布时间】:2021-01-01 05:10:36
【问题描述】:
每天洗牌一次字符串数组的方法是什么?
而且不是每次应用重新启动时。
struct View: View {
@ObservedObject var quotes = Quotes()
var body: some View {
List {
ForEach(quotes.shuffled()) { quote in
Text(quote.quotes)
}
}
}
}
当我在每次更新视图时尝试 shuffled() 方法时,引号会再次被打乱,同样在重新启动应用程序时,我想每天只打乱数组一次。
【问题讨论】:
标签:
ios
arrays
swift
swiftui
shuffle
【解决方案1】:
您需要像用户默认值一样将当前日期存储在内存中,并且每次都检查新日期,就像我在下面的代码中一样。 isNewDay() 函数检查日期是否为新日期并将当前日期保存在用户默认值中。条件 isNewDay() ? quote.shuffled() : 引号 仅当日期为新时才打乱引号
struct View :View{
@ObservedObject var quotes = Quotes()
var body :some View{
List{
ForEach(isNewDay() ? quotes.shuffled() : quotes){ quote in
Text(quote.quotes)
}
}
}
func isNewDay()-> Bool{
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let currentDateString = dateFormatter.string(from: currentDate)
if let lastSaved = UserDefaults.standard.string(forKey: "lastDate"){// last saved date
if lastSaved == currentDateString{
return true
}else{
UserDefaults.standard.setValue(currentDateString, forKey: "lastDate")
return false
}
}else{
UserDefaults.standard.setValue(currentDateString, forKey: "lastDate")
return false
}
}
}