'Random numbers - CGFloat

Is there any idea or better approach do it more nice, elegant way ?

extension UIColor {
    static var randomColor: UIColor {
        .init(
            red: CGFloat(Float.random(in: 0 ... 1.0)),
            green: CGFloat(Float.random(in: 0 ... 1.0)),
            blue: CGFloat(Float.random(in: 0 ... 1.0)),
            alpha: 1.0
        )
    }
}


Solution 1:[1]

Rather than …

CGFloat(Float.random(in: 0 ... 1.0))

… you can use:

CGFloat.random(in: 0...1)

Or, in this context, you can let the compiler infer the type:

extension UIColor {
    static var randomColor: UIColor {
        .init(
            red: .random(in: 0...1),
            green: .random(in: 0...1),
            blue: .random(in: 0...1),
            alpha: 1
        )
    }
}

Solution 2:[2]

Randomize color hue

If you want random red, green, and blue components for your random color, go with @Rob's approach. If you want a randomly selected bright saturated color, randomize the hue.

extension UIColor {
    static var randomHue: UIColor {
        .init(hue: .random(in: 0...1),
              saturation: 1, brightness: 1, alpha: 1)
    }
    static var randomRGB: UIColor {
        .init(red: .random(in: 0...1),
              green: .random(in: 0...1),
              blue: .random(in: 0...1),
              alpha: 1)
    }
}

enter image description here

It really depends what mean by "it" in the text describing what you want. Random components tend to yield dull colors.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rob
Solution 2 pommy