Why The Code Print "0" Instead Of Count Down Integer?

import Foundation
import SwiftUI

struct Foo {
    @State var bar = 0
    @State var timer:Timer? = nil
    let runLoop = RunLoop.main
    
    func setTimer() {
        let timer = Timer(timeInterval: 1, repeats: true, block: { _ in
            bar -= 1
            
            print(bar)
        })
        
        runLoop.add(timer, forMode: .common)
        self.timer = timer
    }
}

Foo().setTimer()

Code Runs

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

@State only works within SwiftUI Views. I’m not sure of the exact mechanism but it seems likely it has no storage unless it’s attached to a view.

2 Likes