swiftuiobservation

Do you actually need to use "import Observation" when using the @Observable macro in SwiftUI


I have used @Observable extensively in a side project to learn more about it. It all seems to be working exactly as expected. But the other day I was watching a Youtube dev show something and noticed that he used import Observation and thus his @Observable was purple.

This may be a dumb question and maybe I have just been lucky that @Obrservable has thus for worked in my small app. I have looked around for an answer and can find almost no-one showing that they import Observation when using the macro.

Do you really need to import Observation to make use of the @Observable macro?


Solution

  • No, you do not need to say import Observation to be able to use @Observable. Observation is exported by Foundation. In the .swiftinterface files of Foundation, it says

    @_exported import Observation
    

    So as long as you import Foundation in some way, directly or indirectly, you will be able to use things declared in Observation.

    This is similar to how you can use things in Foundation (e.g. DateFormatter) when you have only imported SwiftUI, but not Foundation directly.