Chris
Chris

Reputation: 8091

didset not working anymore - trying to find workaround

i found this answer to get the didset back again:

extension Binding {
    /// Execute block when value is changed.
    ///
    /// Example:
    ///
    ///     Slider(value: $amount.didSet { print($0) }, in: 0...10)
    func didSet(execute: @escaping (Value) ->Void) -> Binding {
        return Binding(
            get: {
                return self.wrappedValue
            },
            set: {
                execute($0)
                self.wrappedValue = $0
            }
        )
    }
}

now i tried the same with Published, but got error and don't know how to fix. Error is: Type of expression is ambiguous without more context

@available(iOS 13.0, *)
extension Published {
    /// Execute block when value is changed.
    ///
    /// Example:
    ///
    ///     Slider(value: $amount.didSet { print($0) }, in: 0...10)
    func didSet(execute: @escaping (Value) ->Void) -> Published<Any> {
        return Published ( // error here : Type of expression is ambiguous without more contex`enter code here`
            get: {
                return self.wrappedValue
        },
            set: {
                execute($0)
                self.wrappedValue = $0
        }
        )
    }
}

Upvotes: 0

Views: 232

Answers (1)

Asperi
Asperi

Reputation: 257603

It works, but really for "did set only"... ie.. after direct assignment.

Please consider the following example. Tested with Xcode 11.4 / iOS 13.4

struct FooView: View {
    @ObservedObject var test = Foo()
    var body: some View {
        VStack {
            Button("Test Assign") { self.test.foo = 10 }    // << didSet works !!
            Button("Test Modify") { self.test.foo += 1 }    // xx nope !!
            Divider()
            Text("Current: \(test.foo)")
        }
    }
}

class Foo: ObservableObject {

    @Published var foo: Int = 1 {
        didSet {
            print("foo ==> \(foo)")
        }
    }
}

Upvotes: 1

Related Questions