【问题标题】:didset not working anymore - trying to find workarounddidset 不再工作 - 试图找到解决方法
【发布时间】:2020-04-03 08:12:10
【问题描述】:

我找到了这个答案以再次找回 didset:

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

现在我尝试了与已发布相同的方法,但出现错误并且不知道如何修复。 错误是:表达式类型不明确,没有更多上下文

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

【问题讨论】:

  • Published 没有这样的构造函数。

标签: swiftui


【解决方案1】:

它有效,但真的是 “只设置”...即.. 直接分配后。

请考虑以下示例。使用 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)")
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 2023-02-20
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 2016-07-07
    相关资源
    最近更新 更多