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

Scope of the view property?

During the code challenge we had to set the view.backgroundColor. My question is why am I not able to set this property within the body of the ViewController? For example, I attempted to set this property between the class declaration and the first method and an error comes up about view not being declared.

Only when I attempted to assign the property within the viewDidLoad() did it then work correctly. Can anyone explain why this is?

Thanks!

Can you provide your code along with a link to the code challenge? Thank you!

1 Answer

class ViewController: UIViewController {

let blueColor = UIColor.blueColor()

//: This does NOT work
view.backgroundColor = blueColor

override func viewDidLoad() {
    // Do any additional setup after loading the view, typically from a nib.

    //: This DOES work
    view.backgroundColor = blueColor


}

override func didReceiveMemoryWarning() {
    // Dispose of any resources that can be recreated
}

}

This is my code,

Link to the challenge: https://teamtreehouse.com/library/build-a-simple-iphone-app-with-swift-20/improving-our-user-interface/changing-the-background-color

P.S. let blueColor = UIColor.blueColor()

^^ Doesn't work in newest version, now you use = UIColor.blue