Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Random Color in FunFacts app

Hi,

I was just going through the fun facts app. I was trying to be creative but it didn't work for me. I changed the ColorModel code to the following hoping that it would generate a random color:

import UIKit

struct ColorModel {

    func randomColor() -> UIColor {
        let randomRed = CGFloat(Float(arc4random_uniform(255)))
        let randomGreen = CGFloat(Float(arc4random_uniform(255)))
        let randomBlue = CGFloat(Float(arc4random_uniform(255)))

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

The concept works on playground but when implementing into the FunFacts app, the app crash miserably,

Any suggestion?

Thanks,

Akira

2 Answers

When I'm trying to make a random color in Swift, this is usually how I do it:

func randomColor() -> UIColor{
    func randomNumber() -> CGFloat{
        return CGFloat(drand48())
    }
    return UIColor(red: randomNumber(), green: randomNumber(), blue: randomNumber(), alpha: 1)
}

I use the drand48 function, which produces a Double between 0 and 1. The UIColor constructor is looking for multiple CGFloats between 0 and 1, so I just embed a small function called randomNumber that generates a random CGFloat between 0 and 1 inside of my main randomColor function, so I can reuse randomNumber inside of randomColor. Then, I just call randomNumber() for every argument of the UIColor constructor, and a random color is made


Perhaps a better, more object-oriented approach to this would be to split it up into extensions on both CGFloat and UIColor, like this:

extension CGFloat{
    static func random() -> CGFloat{
        return CGFloat(drand48())
    }
}

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

This does exactly the same thing as the first example, but now you can call it in a simple, easy to find, and predictable line:

UIColor.random()

Awesome, thank you very much for your help :D Will try that out!!