Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Object-Oriented Swift 2.0 Classes Instances of Classes

Class Challenge Help

I apparently do not understand initializers......I do not understand what I have to do at all

2 Answers

Nathan Tallack
Nathan Tallack
22,158 Points

Yeah, they are a little tricky. Especially when sometimes you don't have to write them because they happen automagically (like they do with struct types).

Think of it like this.

The property of a type (that is an immutable value (defined with let) or a mutable value (defined with var)) needs to be set with a value when you first create an object of that class type (unless we consider optionals, but lets ignore that for now).

Consider the following Class type and my use of it. It is a pointless task without methods, but focus on the property.

class Bucket {
    var contents: String

So my Bucket class can allow me to create objects that have a property of contents. But without an initializer method to tell my object how to set that variable I can't use it.

So, I make the initializer to tell it how to set that variable.

class Bucket {
    var contents: String

    init(contents: String) {
        self.contents = contents

So now, that init method (remember, a method is a function inside a class) is used each time I try to create an object of type Bucket. Xcode will prompt me to pass in an parameter of type String named contents. And that init function will assign it to that property (remember, that var that i declare at the start of my class) so that it is configured.

let waterBucket = Bucket(contents: "water") // This creates the object
waterBucket.contents  // This prints out the string "water"

That ability to access the objects property uses another method called a "getter" which is automagically created for your class by the compiler. But like optionals, that is another lesson for another time. ;)

Thank you so much! I appreciate your help. That helps me out a lot.