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 Object-Oriented Swift 2.0 Classes Recap: Classes

Boris Likhobabin
Boris Likhobabin
3,581 Points

Is initializer an instance of a class/struct itself?

Is initializer an instance of a class/struct itself?

1 Answer

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Boris Likhobabin,

An initializer is a method thats called to create an instance of a class or struct. It's defined using the init keyword in Swift. The purpose of the initializer is to ensure that an object is ready for use, this means all of its stored properties must have values.

Example:

class Person {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

Our Person class has two properties, name and age. This means to create an instance of this class, we have to pass the values to populate these properties into the initializer.

Creating the instance:

let personInstance = Person(name: "Steven", age: 23)

We now have an instance of the Person class called personInstance.

Good Luck