Skip to content

0x051-Swift-Macro

Observable宏说明

swift
/// A type that emits notifications to observers when underlying data changes. 一种在底层数据发生变化时向观察者发送通知的类型
/// Conforming to this protocol signals to other APIs that the type supports observation. However, applying the `Observable` protocol by itself to a type doesn't add observation functionality to the type. Instead, always use the ``Observation/Observable()`` macro when adding observation support to a type. 遵循了此协议表明该类型支持观察。然而,仅将 `Observable` 协议应用于某个类型并不会为该类型添加观察功能。相反,在为类型添加观察支持时,起作用的是增加的 `Observation/Observable()` 宏。(也就是说Observable只是标记作用,真正起作用的是`Observation/Observable()` 宏)
@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
public protocol Observable {
}


/// 定义并实现 `Observable` 协议的一致性。
/// 此宏为自定义类型添加观察支持并使该类型遵循 `Observation/Observable` 协议。例如,以下代码将 `Observable` 宏应用于 `Car` 类型,使其可被观察
///     @Observable 
///     class Car {
///        var name: String = ""
///        var needsRepairs: Bool = false
///        init(name: String, needsRepairs: Bool = false) {
///            self.name = name
///            self.needsRepairs = needsRepairs
///        }
///     }
@attached(member, names: named(_$observationRegistrar), named(access), named(withMutation)) @attached(memberAttribute) @attached(extension, conformances: Observable) public macro Observable() = #externalMacro(module: "ObservationMacros", type: "ObservableMacro")
/// A type that emits notifications to observers when underlying data changes. 一种在底层数据发生变化时向观察者发送通知的类型
/// Conforming to this protocol signals to other APIs that the type supports observation. However, applying the `Observable` protocol by itself to a type doesn't add observation functionality to the type. Instead, always use the ``Observation/Observable()`` macro when adding observation support to a type. 遵循了此协议表明该类型支持观察。然而,仅将 `Observable` 协议应用于某个类型并不会为该类型添加观察功能。相反,在为类型添加观察支持时,起作用的是增加的 `Observation/Observable()` 宏。(也就是说Observable只是标记作用,真正起作用的是`Observation/Observable()` 宏)
@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
public protocol Observable {
}


/// 定义并实现 `Observable` 协议的一致性。
/// 此宏为自定义类型添加观察支持并使该类型遵循 `Observation/Observable` 协议。例如,以下代码将 `Observable` 宏应用于 `Car` 类型,使其可被观察
///     @Observable 
///     class Car {
///        var name: String = ""
///        var needsRepairs: Bool = false
///        init(name: String, needsRepairs: Bool = false) {
///            self.name = name
///            self.needsRepairs = needsRepairs
///        }
///     }
@attached(member, names: named(_$observationRegistrar), named(access), named(withMutation)) @attached(memberAttribute) @attached(extension, conformances: Observable) public macro Observable() = #externalMacro(module: "ObservationMacros", type: "ObservableMacro")

从此处开始

参考:https://juejin.cn/post/7283691376650223652
https://juejin.cn/post/7253042571215716412