gpt4 book ai didi

ios - @Published 属性包装器及其 wrappedValue

转载 作者:行者123 更新时间:2023-11-28 05:36:58 25 4
gpt4 key购买 nike

当您定义自己的属性包装器时,您必须指定一个名为“wrappedValue”的非静态属性。例如:

@propertyWrapper
struct MyPropertyWrapper<Value> {
var value: Value
}

对于上面的代码,编译器会提示:

Property wrapper type 'MyPropertyWrapper' does not contain a non-static property named 'wrappedValue'

因此,您只需执行以下操作即可修复错误:

@propertyWrapper
struct MyPropertyWrapper<Value> {
var value: Value

var wrappedValue: Value {
get {
value
}
set {
value = newValue
}
}
}

只是举一些例子,这对于 @State 是正确的:

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
@propertyWrapper public struct State<Value> : DynamicProperty {

/// The current state value.
public var wrappedValue: Value { get nonmutating set }
}

@Binding 也是如此:

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
@propertyWrapper @dynamicMemberLookup public struct Binding<Value> {

/// The value referenced by the binding. Assignments to the value
/// will be immediately visible on reading (assuming the binding
/// represents a mutable location), but the view changes they cause
/// may be processed asynchronously to the assignment.
public var wrappedValue: Value { get nonmutating set }
}

等等。但是 @Published 属性包装器没有包装值:

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
@propertyWrapper public struct Published<Value> {

/// Initialize the storage of the Published property as well as the corresponding `Publisher`.
public init(initialValue: Value)

/// A publisher for properties marked with the `@Published` attribute.
public struct Publisher : Publisher {

/// The kind of values published by this publisher.
public typealias Output = Value

/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = Never

/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where Value == S.Input, S : Subscriber, S.Failure == Published<Value>.Publisher.Failure
}

/// The property that can be accessed with the `$` syntax and allows access to the `Publisher`
public var projectedValue: Published<Value>.Publisher { mutating get }
}

我在这里肯定遗漏了一些东西,因为编译器不会让您创建没有 wrappedValue 的属性包装器。在这种情况下,与其他属性包装器有何不同?

最佳答案

您显示的代码不是@Published实际实现 - 它只是公开可见的界面。如果将该代码粘贴到 Xcode 中,您将在 wrappedValue 等方面遇到相同的错误;该代码无法编译。

wrappedValue 的访问级别为 internal - 因此我们可以假设 @Published 的实际实现声明了类似 internal 的内容var wrappedValue:Value.这满足了属性包装器要求,但意味着 wrappedValue 在其框架之外不可见。

关于ios - @Published 属性包装器及其 wrappedValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58330248/

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