✅ Stable Random Color
It's easy to generate random colors when you know colors are made from numbers. So just pass in random values from 0.0
to 1.0
. But many times you actually wanted to keep the random color without actually storing it.
Here is how you can generate random colors based on a seed (like for example the userID
) which always be the same:
/// - Note: Make it `Color` for SwiftUI
extension UIColor {
static func random(seed: Int) -> Self {
var generator = RandomNumberGenerator(seed: seed)
return .init(
red: .random(in: (0...1), using: &generator),
green: .random(in: (0...1), using: &generator),
blue: .random(in: (0...1), using: &generator)
, alpha: 1 // Remove this line for the `SwiftUI.Color`
)
}
}
And here is the random number generator behind this:
struct RandomNumberGenerator: Swift.RandomNumberGenerator {
init(seed: Int) { srand48(seed) }
func next() -> UInt64 { UInt64(drand48() * Double(UInt64.max)) }
}
SwiftUI Example:
The following will always be the same and doesn't change on each run (nor each preview).
Note that you can use the random generator in a way that matches your needs
static func random() -> CGFloat
is useless outside ofstatic func random() -> UIColor
so you can declare the first method inside the second one – Chaisson