Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add constant method to support SwiftUI previews and tests #187

Closed

Conversation

MikhailGasanov
Copy link

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

  • Added a constant(_:) method to the Default extension.
  • The method creates a Default instance with a specified constant value, particularly useful for SwiftUI previews and testing scenarios.
  • Updated documentation to include a usage example within a SwiftUI preview.

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

  • Unit tests have been added to verify that the constant(_:) method correctly initializes Default instances with the specified constant values.
  • Manual testing has been performed to ensure that the method works seamlessly in SwiftUI previews.

Additional Notes

  • This new functionality is backward-compatible and doesn’t affect any existing code.
  • It is particularly helpful for scenarios where you need to isolate and test UI components with predictable data.

@MikhailGasanov MikhailGasanov mentioned this pull request Aug 31, 2024
@sindresorhus
Copy link
Owner

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()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants