robb/atrandom
A property wrapper that assigns a stable random value to a member variable, persisting across multiple `body` invocations.
Fixed Seeds
By default, different instances of the same View or ViewModifier generate unique @Random values. To ensure consistency, you can provide a custom seed via the property wrapper’s projectedValue's seed value.
For example, assigning a model’s hashValue to $greeting.seed ensures stability when the view gets recreated, say in a LazyVStack.
struct Cell: View {
@Random(in: "Hello", "Bonjour", "Willkommen") var greeting
var model: Model
init(model: Model) {
self.model = model
$greeting.seed = model.hashValue
}
var body: some View {
// The same `model` will get the same `greeting`, every time.
Text("\(greeting), \(model.name)!")
}
}This way, each Cell instance with the same model will always produce the same greeting.
[!IMPORTANT] Some Swift types, like
String, generate differenthashValuesacross app launches. For values that persist across launches, use a stable identifier, such as a user ID.
Package Metadata
Repository: robb/atrandom
Default branch: main
README: README.md