Search code examples
swift

Swift @Observable vs Observable protocol


What's the difference between @Observable and conforming to Observable? Are they functionally equivalent?

@Observable class MyClass { ... }
class MyClass: Observable { ... }

Solution

  • @Observable is a macro and Observable is a protocol

    Observable

    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.

    @Observable

    This macro adds observation support to a custom type and conforms the type to the Observable protocol.

    Always use the Observable() macro when adding observation support to a type.