Optional State or Binding in SwiftUI

Viewed 2358

I would like to ask question about SwiftUI behaviour when I am using .onChange( value) { }

Why If I am using @State var some: SomeType? with optional type and then @Binding var some: SomeType this operator only detects changes it there is change from some SomeType value to nil and vice versa. But changes to underlying object values are not detected as changes

ex. @Binging var progress: Int?

changing progress from nil to 100 detectes changes but if I change values from 1 -> 2 -> 3 they are skipped It works if I use @Binding var progress: Int

Any Idea how to use Optionals with onChange() ?

1 Answers

Here is working example of optional with State and Binding:


import SwiftUI

struct ContentView: View {
    
    @State private var progress: Int?
    
    var body: some View {
        
        CustomView(progress: $progress)
        
    }
}

struct CustomView: View {
    
    @Binding var progress: Int?
    
    var body: some View {
        
        Button("update") {
            
            if let unwrappedInt = progress { progress = unwrappedInt + 1 } 
            else { progress = 0 }         //<< █ █ Here: initializing! █ █
            
        }
        .onChange(of: progress) { newValue in
            
            if let unwrappedInt = progress { print(unwrappedInt) }
            
        }

    }
}
Related