Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional State or Binding in SwiftUI

Tags:

swift

swiftui

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. @Binding 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() ?

like image 549
Michał Ziobro Avatar asked Aug 08 '26 11:08

Michał Ziobro


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

    }
}
like image 72
ios coder Avatar answered Aug 10 '26 07:08

ios coder