How to make a random color with Swift

You're going to need a function to produce random CGFloats in the range 0 to 1:

extension CGFloat {
    static func random() -> CGFloat {
        return CGFloat(arc4random()) / CGFloat(UInt32.max)
    }
}

Then you can use this to create a random colour:

extension UIColor {
    static func random() -> UIColor {
        return UIColor(
           red:   .random(),
           green: .random(),
           blue:  .random(),
           alpha: 1.0
        )
    }
}

If you wanted a random alpha, just create another random number for that too.

You can now assign your view's background colour like so:

self.view.backgroundColor = .random()

For Swift 4.2

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

For Swift 3 and above:

extension CGFloat {
    static var random: CGFloat {
        return CGFloat(arc4random()) / CGFloat(UInt32.max)
    }
}

extension UIColor {
    static var random: UIColor {
        return UIColor(red: .random, green: .random, blue: .random, alpha: 1.0)
    }
}

Usage:

let myColor: UIColor = .random

Make a function to generate random color:

func getRandomColor() -> UIColor {
     //Generate between 0 to 1
     let red:CGFloat = CGFloat(drand48())   
     let green:CGFloat = CGFloat(drand48()) 
     let blue:CGFloat = CGFloat(drand48())  

     return UIColor(red:red, green: green, blue: blue, alpha: 1.0)
}

Now, you can call this function whenever you need random color.

self.view.backgroundColor = getRandomColor()

For random solid colors you can use UIColor HSB initializer and randomize only the hue:

extension UIColor {
    static var random: UIColor {
        return .init(hue: .random(in: 0...1), saturation: 1, brightness: 1, alpha: 1)
    }
}

let color1: UIColor = .random
let color2: UIColor = .random
let color3: UIColor = .random
let color4: UIColor = .random
let color5: UIColor = .random

enter image description here


SwiftUI - Swift 5

import SwiftUI

extension Color {
    static var random: Color {
        return Color(red: .random(in: 0...1),
                     green: .random(in: 0...1),
                     blue: .random(in: 0...1))
    }
}

Usage:

let randomColor: Color = .random