How to make a random color with Swift

SwiftRandomColorsUicolorFunc

Swift Problem Overview


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

Swift Solutions


Solution 1 - 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()

Solution 2 - Swift

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

Solution 3 - Swift

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

Solution 4 - Swift

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

Solution 5 - Swift

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

Solution 6 - Swift

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.

Solution 7 - Swift

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

Solution 8 - Swift

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

Solution 9 - Swift

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

Solution 10 - Swift

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

Solution 11 - Swift

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGiovanie RodzView Question on Stackoverflow
Solution 1 - SwiftABakerSmithView Answer on Stackoverflow
Solution 2 - SwiftOrkhan AlikhanovView Answer on Stackoverflow
Solution 3 - SwiftBhavin RamaniView Answer on Stackoverflow
Solution 4 - SwiftLeo DabusView Answer on Stackoverflow
Solution 5 - SwiftXeazaView Answer on Stackoverflow
Solution 6 - SwiftleogdionView Answer on Stackoverflow
Solution 7 - SwiftSentry.coView Answer on Stackoverflow
Solution 8 - SwiftTimBigDevView Answer on Stackoverflow
Solution 9 - SwiftRaksha.View Answer on Stackoverflow
Solution 10 - SwiftAlex ChaseView Answer on Stackoverflow
Solution 11 - SwiftbungditoView Answer on Stackoverflow