Sajjon / swift-perception

Observable tools, backported.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Perception

CI Slack

Observation tools for platforms that do not officially support observation.

Learn More

This library was created by Brandon Williams and Stephen Celis, who host the Point-Free video series which explores advanced Swift language concepts.

video poster image

Overview

The Perception library provides tools that mimic @Observable and withObservationTracking in Swift 5.9, but they are backported to work all the way back to iOS 13, macOS 10.15, tvOS 13 and watchOS 6. This means you can start taking advantage of Swift 5.9's observation tools today, even if you can't drop support for older Apple platforms. Using this library's tools works almost exactly as using the official tools, but with one small exception.

To begin, mark a class as being observable by using the @Perceptible macro instead of the @Observable macro:

@Perceptible
class FeatureModel {
  var count = 0
}

Then you can hold onto a perceptible model in your view using a regular let property:

struct FeatureView: View {
  let model: FeatureModel

  // ...
}

And in the view's body you must wrap your content using the WithPerceptionTracking view in order for observation to be correctly hooked up:

struct FeatureView: View {
  let model: FeatureModel

  var body: some View {
    WithPerceptionTracking {
      Form {
        Text(model.count.description)
        Button("Increment") { model.count += 1 }
      }
    }
  }
}

It's unfortunate to have to wrap your view's content in WithPerceptionTracking, however if you forget then you will helpfully get a runtime warning letting you know that observation is not set up correctly:

🟣 Runtime Warning: Perceptible state was accessed but is not being tracked. Track changes to state by wrapping your view in a 'WithPerceptionTracking' view.

Community

If you want to discuss this library or have a question about how to use it to solve a particular problem, there are a number of places you can discuss with fellow Point-Free enthusiasts:

Documentation

The latest documentation for the Perception APIs is available here.

License

This library is released under the MIT license. See LICENSE for details.

About

Observable tools, backported.

License:MIT License


Languages

Language:Swift 99.7%Language:Makefile 0.3%