Coding

Generate a Random Color in Swift

by
published on
So there are multiple ways to do this.
Random color using swift
Here is one of the way. What i am doing below is generate 3 random numbers for RGB colour code (Red, Green, Blue) and then generating a UIColor object out of it. Note that UIColor object only expects the colour values to be in decimals between 0 to 1 and so i thought drand48 should be the best way to do. If you think there is a better way let me know.
    func getRandomColor() -> UIColor{

        var randomRed:CGFloat = CGFloat(drand48())

        var randomGreen:CGFloat = CGFloat(drand48())

        var randomBlue:CGFloat = CGFloat(drand48())

        return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)

    }
In the above code i have use the drand48() method to generate a random number between 0 to 1.  These functions generate pseudo-random numbers using the linear congruential algorithm and 48-bit integer arithmetic.To learn more about this method you can refer this page. Also note that the drand48()  returns a Double value whereas the UIColour init method expects the value to be in CGFloat. I am not sure if there is any alternative to CGFloat for swift but i can use it directly. So i just type casted it to CGFloat. Other alternative options would be using  arc4random_uniform method and then MOD it to get a decimal value.