110

How I can make a random color function using Swift?

import UIKit

class ViewController: UIViewController {

    var randomNumber = arc4random_uniform(20)
    var randomColor = arc4random()

    //Color Background randomly
    func colorBackground() {

        // TODO: set a random color
        view.backgroundColor = UIColor.yellow

    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Giovanie Rodz
  • 1,741
  • 3
  • 12
  • 7

12 Answers12

220

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()
ScottyBlades
  • 12,189
  • 5
  • 77
  • 85
ABakerSmith
  • 22,759
  • 9
  • 68
  • 78
  • 1
    `static func random() -> CGFloat` is useless outside of `static func random() -> UIColor` so you can declare the first method inside the second one – Vyachaslav Gerchicov Sep 04 '20 at 08:53
  • 1
    In recent versions of Swift, most (all?) scalar types have a `random(in:)` function that returns random values. For CGFloat that function is `static func random(in range: ClosedRange) -> CGFloat` So you can just use `.random(in: 0...1)`. No need for your custom `random()` function. – Duncan C Jan 05 '23 at 14:14
125

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
aheze
  • 24,434
  • 8
  • 68
  • 125
Orkhan Alikhanov
  • 9,122
  • 3
  • 39
  • 60
37

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()
Bhavin Ramani
  • 3,221
  • 5
  • 30
  • 41
  • here if any body want to know more about CGFLoat https://developer.apple.com/documentation/coregraphics/cgfloat – bungdito Jul 11 '18 at 03:17
35

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

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 1
    Check your screenshot: what was the probability to get your perfect yellow (second result)? – Cœur Nov 27 '19 at 17:10
  • You can fine tune the odds using integers and determining now many steps you want in the hue range – Leo Dabus Nov 27 '19 at 17:14
  • I believe the odds were about 1 out of 6000 for this yellow: there aren't any rounding to Int8 being done, so you had 1 chance of 1000 to get a float smaller than 0.0005 or bigger than 0.9995. And then there are 6 edges possibles (0 0 1, 0 1 0, 0 1 1, 1 0 0, 1 0 1, 1 1 0). – Cœur Dec 01 '19 at 06:12
  • 1
    I think you are right I came up with the odds of 1 out of 6666 to generate a float in range `0.16659 ... 0.16674` – Leo Dabus Dec 01 '19 at 10:09
25

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

Community
  • 1
  • 1
Xeaza
  • 1,410
  • 1
  • 17
  • 21
14

With Swift 4.2, you can simplify this by using the new random functions which have been added:

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

There are more details here.

leogdion
  • 2,332
  • 1
  • 19
  • 21
  • Hi. if i want to random in range from red -> yellow. Can u provide some suggest? – famfamfam Jan 30 '19 at 09:51
  • 1
    Great question @famfamfam I would then (instantiate based on hue, saturation, and brightness)[https://developer.apple.com/documentation/uikit/uicolor/1621931-init]. The hue for yellow would be the midpoint of green and red. Red is 0 and Green is 1/3. Therefore yellow would be 1/6. So let's assume you want a constant saturation and brightness and orange as your midpoint then I would do: ```UIColor(hue: CGFloat.random(in: 0...1.0/6.0), saturation: 1.0, brightness: 1.0, alpha: 1.0)``` For turquoise to be your mid-point then your hue would be: ```CGFloat.random(in: 1.0/6.0...1.0)``` – leogdion Jan 30 '19 at 16:17
12

Swift 4.2

I'm adding this answer because it uses a different approach, and because many of the previous answers requires additional syntactic sugar, which in my opinion shouldn't be preferred. Vanilla Swift for the win.

extension UIColor {
    /**
     * Returns random color
     * ## Examples: 
     * self.backgroundColor = UIColor.random
     */
    static var random: UIColor {
        let r:CGFloat  = .random(in: 0...1)
        let g:CGFloat  = .random(in: 0...1)
        let b:CGFloat  = .random(in: 0...1)
        return UIColor(red: r, green: g, blue: b, alpha: 1)
    }
}
Sentry.co
  • 5,355
  • 43
  • 38
5

Swift 4.2 Extension

extension UIColor {

    convenience init(red: Int, green: Int, blue: Int) {
        assert(red >= 0 && red <= 255, "Invalid red component")
        assert(green >= 0 && green <= 255, "Invalid green component")
        assert(blue >= 0 && blue <= 255, "Invalid blue component")

        self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
    }

    convenience init(rgb: Int) {
        self.init(
            red: (rgb >> 16) & 0xFF,
            green: (rgb >> 8) & 0xFF,
            blue: rgb & 0xFF
        )
    }

    static func random() -> UIColor {
        return UIColor(rgb: Int(CGFloat(arc4random()) / CGFloat(UINT32_MAX) * 0xFFFFFF))
    }

}

Usage:

let color = UIColor.random()
TimBigDev
  • 511
  • 8
  • 7
5

Swift 5.1

Make This function and generate Random color.

e.g. view.backgroundColor = random()

func random() -> UIColor {
        return UIColor(red: .random(in: 0...1),
                       green: .random(in: 0...1),
                       blue: .random(in: 0...1),
                       alpha: 1.0)
    }
Raksha.
  • 479
  • 6
  • 6
1

Using an extension with an inline function to generate randoms

extension UIColor {
    static func random() -> UIColor {

        func random() -> CGFloat { return .random(in:0...1) }

        return UIColor(red:   random(),
                       green: random(),
                       blue:  random(),
                       alpha: 1.0)
    }
}
Alex Chase
  • 960
  • 1
  • 7
  • 11
1

Swift 5.8.1 Extension

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

Usage

let randomColor = UIColor.random
print(randomColor)
Hassan Taleb
  • 2,350
  • 2
  • 19
  • 24
0
func anotherGetRandomColor()->UIColor{

    let newRed   = Double(arc4random_uniform(256))/255.0
    let newGreen = Double(arc4random_uniform(256))/255.0
    let newBlue  = Double(arc4random_uniform(256))/255.0

    return UIColor(red: CGFloat(newRed), green: CGFloat(newGreen), blue: CGFloat(newBlue), alpha: 1.0)
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
bungdito
  • 3,556
  • 4
  • 31
  • 38
  • 1
    The entropy of this code is 255*255*255, which could be weak. Better generate floating values instead of small integers. On top of that, `arc4random_uniform(255)` will only give values from 0 to 254, so you're biased toward darker colors. – Cœur Sep 17 '18 at 10:41
  • 1
    @Cœur besides that his division is flawed because he initialized CGFloat after dividing a value in the range 0...254 / 255 which would cause to zero all results – Leo Dabus Nov 27 '19 at 16:46