Skip to content

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

Closed
MikhailGasanov wants to merge 1 commit into
sindresorhus:mainfrom
MikhailGasanov:add-constant-method
Closed

MikhailGasanov wants to merge 1 commit into
sindresorhus:mainfrom
MikhailGasanov:add-constant-method

Conversation

@MikhailGasanov

Copy link
Copy Markdown

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鈥檚 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鈥檛 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
Copy Markdown
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