Skip to content

Instantly share code, notes, and snippets.

@chockenberry
Created August 15, 2023 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chockenberry/c3a5ba9c0a605bea5ebda62734cbdf4c to your computer and use it in GitHub Desktop.
Save chockenberry/c3a5ba9c0a605bea5ebda62734cbdf4c to your computer and use it in GitHub Desktop.
THE BEST ENHANCEMENT: Extend #if targetEnvironment() for Previews, Widgets, and More.
We have this in SwiftUI:
#if targetEnvironment(simulator)
Yet it’s rarely useful, because SwiftUI code that’s being used in a preview is being run in a simulator.
The distinction that developers need is whether the code is being used in a preview or in the Simulator app.
The root of the problem is that View data is kept in two separate locations:
Previews: ~/Library/Developer/Xcode/UserData/Previews/Simulator Devices/
Simulator app: ~/Library/Developer/CoreSimulator/Devices/
When working in a dynamic environment like SwiftUI, you will often want to experiment using model data that’s not kept in a shared location like a group container or AppStorage. You may also want to adjust model data to see what edge cases look like. Something like this would let you do this without affecting the code paths you want to use in a real app:
#if targetEnvironment(preview)
A similar issue, not necessarily related to SwiftUI, is that the code you want to execute in the context of an app is often very different than that of an extension (e.g. primarily widgets, but can be other types such as a photo editing extension).
These extension contexts often come with limited resources (both processing time and memory footprint). Something like this would let the developer deal with these disparate situations:
#if targetEnvironment(widget)
An example here would be using a lightweight model based on UserDefaults or a group container for the Widget case, and a more expressive model with a database backing store, networking, etc. when compiling for the app.
This has been a longstanding need for developers. Here is a three year old post on Stack Overflow:
https://stackoverflow.com/questions/58759987/how-do-you-check-if-swiftui-is-in-preview-mode
SO BEST ENHANCEMENT PLS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment