Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

ios - SwiftUI - how to shuffle an array one time a day?

What is the approach to shuffle an array of strings one time a day? And not every time the app is relaunches.

struct View: View {
    @ObservedObject var quotes = Quotes()
    var body: some View {
        List {
            ForEach(quotes.shuffled()) { quote in
                Text(quote.quotes)
            }
        }
    }
}

When I try the shuffled() method every time the view is updated the quotes are shuffled again, also when relaunching the app, I want to shuffle the array only one time a day.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to store current date in memory like user defaults and check every time for new date like I have in code below. isNewDay() function checks if date is new and saves current date in user defaults. Condition isNewDay() ? quotes.shuffled() : quotes shuffles quotes only if date is new

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
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...