Home > OS >  Random numbers - CGFloat
Random numbers - CGFloat

Time:04-07

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

CodePudding user response:

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

CodePudding user response:

This is extension for random numbers of Float.

Swift 3 & 4 & 5 syntax

// MARK: Float Extension

 public extension Float {

/// Returns a random floating point number between 0.0 and 1.0, inclusive.
static var random: Float {
    return Float(arc4random()) / 0xFFFFFFFF
}

/// Random float between 0 and n-1.
///
/// - Parameter n:  Interval max
/// - Returns:      Returns a random float point number between 0 and n max
static func random(min: Float, max: Float) -> Float {
    return Float.random * (max - min)   min
  }
}

Use :

let randomNumFloat   = Float.random(min: 6.98, max: 923.09)
  • Related