gpt4 book ai didi

swift - 将自定义属性包装器与 @Published 结合使用

转载 作者:行者123 更新时间:2023-12-04 14:26:34 25 4
gpt4 key购买 nike

我希望将自定义属性包装器应用于已包装在 @Published 中的变量。 ,嵌套它们像
(一) @Custom @Published var myVar或者
(B) @Published @Custom var myVar(注意包装器的应用顺序)。
在 (A) 的情况下,我收到错误

'wrappedValue' is unavailable: @Published is only available on properties of classes


对于(B)

error: key path value type 'Int' cannot be converted to contextual type 'Updating<Int>'


两者都不是特别有用。任何想法如何使它工作?
最小代码示例
import Combine

class A {
@Updating @Published var b: Int

init(b: Int) {
self.b = b
}
}

@propertyWrapper struct Updating<T> {
var wrappedValue: T {
didSet {
print("Update: \(wrappedValue)")
}
}
}

let a = A(b: 1)
let cancellable = a.$b.sink {
print("Published: \($0)")
}
a.b = 2
// Expected output:
// ==> Published: 1
// ==> Published: 2
// ==> Update: 2

最佳答案

我找到的唯一解决方案是一种解决方法:制作自定义 @propertyWrapper有一个 @Published里面的属性(property)。
例子:

/// Workaround @Published not playing nice with other property wrappers. 
/// Use this to replace @Published to temporarily help debug a property being accessed off the main thread.

@propertyWrapper
public class MainThreadPublished<Value> {
@Published
private var value: Value


public var projectedValue: Published<Value>.Publisher {
get {
assert(Thread.isMainThread, "Accessing @MainThread property on wrong thread: \(Thread.current)")
return $value
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
set {
assert(Thread.isMainThread, "Accessing @MainThread property on wrong thread: \(Thread.current)")
$value = newValue
}
}

public var wrappedValue: Value {
get {
assert(Thread.isMainThread, "Accessing @MainThread property on wrong thread: \(Thread.current)")
return value
}
set {
assert(Thread.isMainThread, "Accessing @MainThread property on wrong thread: \(Thread.current)")
value = newValue
}
}

public init(wrappedValue value: Value) {
self.value = value
}

public init(initialValue value: Value) {
self.value = value
}
}
进一步阅读:
  • 属性包装器提案:https://github.com/apple/swift-evolution/blob/main/proposals/0258-property-wrappers.md#referencing-the-enclosing-self-in-a-wrapper-type
  • 不是 Apple 的 @Published 来源,而是一个有用的例子:https://github.com/OpenCombine/OpenCombine/blob/master/Sources/OpenCombine/Published.swift

  • 编辑:
    我也刚刚发现这篇文章可能提供了另一种方法,但我没有时间调查:
  • 嵌套属性包装器:https://noahgilmore.com/blog/nesting-property-wrappers/
  • 关于swift - 将自定义属性包装器与 @Published 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66118723/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com