Home > Software design >  perform action every 3 time in each in for loop
perform action every 3 time in each in for loop

Time:09-21

I had a function for setting up a timer, how can I perform an action every 3 times in each(1,2,3 and 4 = 1 ,5 = 2, 6 = 3) still 6 or more in for loop?

func duration(interval:Double,rep:Int){
        let queue = DispatchQueue.main
        let timer = DispatchSource.makeTimerSource(queue: queue)
        var num = 0
        for i in 0...12{
            if (i%3 == 0){
perform something
num   
              }else if (i%2 == 0){
perform something
num   
              }else{
perform something   
num              
}
        if num == 12{
         timer.cancel()         
}
        }



    }```

CodePudding user response:

The SwiftUI way to do this is a Timer publisher.

Example:

struct ContentView: View {
    @State private var number = 0
    @State private var multiple: Int?
    private let startDate = Date()
    private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        VStack {
            Text("Number: \(number)")

            Text("Multiple: \(multiple != nil ? String(multiple!) : "no")")
        }
        .onReceive(timer) { date in
            let interval = Int(date.timeIntervalSince(startDate))
            print(interval)
            number = interval

            if interval.isMultiple(of: 3) {
                // multiple of 3
                multiple = 3
            } else if interval.isMultiple(of: 2) {
                // multiple of 2 (careful - 6 will be ignored because it is already a multiple of 3)
                multiple = 2
            } else {
                // neither multiple of 2 or 3
                multiple = nil
            }

            if interval == 12 {
                timer.upstream.connect().cancel()
            }
        }
    }
}

Result:

  • Related