Silver Challenge - View Controllers

Here’s how I resolved the Silver Challenge:

import UIKit

class ConversionViewController: UIViewController {
    var randomFloat: CGFloat {
        return CGFloat(Float.random(in: 0.0...1.0))
    override func viewDidLoad() {
        print("ConversionViewController loaded its view.")
    override func viewWillAppear(_ animated: Bool) {
        let randomColor = UIColor(red: randomFloat, green: randomFloat, blue: randomFloat, alpha: 1.0)
        view.backgroundColor = randomColor

Basically, I used the UIColor initializer that lets you use floats for the red, green and blue colors and passed them a random float between 0.0 and 1.0 (inclusive). The alpha parameter (the color’s opacity) is set to 1.0 so that it would always be visible. To create the random float, I used a computed property of type CGFloat (as that is what the UIColor initializer requires for its values) so it would be a different CGFloat each time the randomFloat property was accessed. Finally, I set the view’s background to the generated random color.

Edit: Looks like I could’ve also used CGFloat.random() directly to avoid casting the Float to a CGFloat in my computed property. Oh well…

In your code are the red, green and blue components equal? I used a separate random value for each:

override func viewWillAppear(_: Bool) {
    let red = CGFloat(Float(arc4random()) / (Float(UINT32_MAX)))
    let blue = CGFloat(Float(arc4random()) / (Float(UINT32_MAX)))
    let green = CGFloat(Float(arc4random()) / (Float(UINT32_MAX)))
    print(red, blue, green)
    view.backgroundColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0)

Hi. No, it’s a different value each time the computed property randomFloat is accessed (once for red, another time for green and finally once more for blue) in the UIColor initializer.