sindresorhus / Defaults

💾 Swifty and modern UserDefaults
https://swiftpackageindex.com/sindresorhus/Defaults/documentation/defaults
MIT License
2.02k stars 121 forks source link

Add `constant` method to support SwiftUI previews and tests #187

Closed MikhailGasanov closed 2 months ago

MikhailGasanov commented 2 months ago

Description

This PR introduces a constant method to the Default extension, allowing developers to easily create default values that can be used in SwiftUI previews and unit tests. This addition simplifies the process of providing mock data and ensures that default values are consistent across different components of the app.

Key Changes

Usage Example

Here’s how you can use the new constant method in a SwiftUI preview:

extension Defaults.Keys {
    static let hasUnicorn = Key<Bool>("hasUnicorn", default: false)
}

struct ContentView: View {
    @Default(.hasUnicorn) var hasUnicorn

    var body: some View {
        Toggle("Toggle", isOn: $hasUnicorn)
    }
}

#Preview {
    ContentView(hasUnicorn: .constant(true))
}

In this example, the constant method is used to set up a mock for hasUnicorn key, making it easy to visualize the view with a predefined value during development.

Testing

Additional Notes

sindresorhus commented 2 months ago

Thanks for working on this, but I don't think this is the optimal way to solve this problem. @State and also @Default should generally be private, so you wouldn't be able to just pass in values, and changing views like that to accommodate preview is generally the wrong approach. In addition, if we were to add a .constant() thing, it should not actually write to UserDefaults at all.

For preview specifically, the right solution is to use https://developer.apple.com/documentation/SwiftUI/Previewable()