How to make a random background color with Swift


How I can make a random background color function using Swift?

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var numberScreen = arc4random_uniform(20)
    var backgroundColor = arc4random()

    @IBOutlet weak var perfbadLabel: UILabel!
    @IBOutlet weak var randomNumber: UILabel!
    @IBOutlet weak var countLabel: UILabel!
    @IBOutlet weak var levelLabel: UILabel!

    var timer = NSTimer()
    var flashTimer = NSTimer()
    var count = 40
    var labelcount = 1
    var velocity = 0.25

    //Color Background
    func colorBackground() {

        self.view.backgroundColor = UIColor.yellowColor()


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