How can I use willSet to update or correct some value in Swift?

Viewed 668

I want use willSet to control a condition, and make necessary job for setting right value, but willSet did not help to make condition happen! The value still gets bigger than 5, what am I doing wrong?

import SwiftUI

struct ContentView: View {

    @State private var value: Int = Int() {
        
        willSet(newValue) {
            
            if newValue > 5 {
                
                value = 5
            }
            
        }
  
    }

    var body: some View {
        Text(value.description)
            .padding()
        
        Button("random update") { value = Int.random(in: 0...10) }
    }
}
1 Answers

use didSet instead

struct Foo {
    var value: Int = 0 {
        didSet {
            if value > 5 {
                value = 5
            }
        }
    }
}

var foo = Foo()
foo.value = 6
print(foo.value) // 5

EDIT:

To illustrate that value will be set to 5 before observed as 6:

import SwiftUI

struct MySwiftUIView: View {
    @State private var value: Int = 0 {
        didSet {
            print("setting value to \(value)")
            
            if value > 5 {
                value = 5
            }
        }
    }
    
    var body: some View {
        VStack {
            Text(valueAsText)
                .padding()
            Button("Set value to >5") { value = 6 }
        }
    }
    
    private var valueAsText: String {
        print("value: \(value)")
        
        return "\(value)"
    }
}

struct MySwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        MySwiftUIView()
    }
}

where tapping the button will output the following:

value: 0
setting value to 6
setting value to 5
value: 5
Related