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

Freshmen programmer, not quite getting the purpose of initializers and instances in Swift. I need a basic understanding.

Need help what's the purpose of getting an initial value of a collection of data?

1 Answer

When you create an object, all its properties must have an initial value (the exception are Optional types). You can assign an initial value in two ways: direct assign at declaration or with an initializer (init).

class Foo {
  var bar: Int = 0 // direct assign
}

In this example the class Foo has one property initialized directly, but lets say you don't have a sensible initial value and you need to receive that value from somewhere else, you create an init method:

class Foo {
  var bar: Int
  init(bar: Int) {
    self.bar = bar
  }
}

The init method receives an int as a parameter, and assigns this parameter to the bar property (the word self refers to the property, otherwise it would be an ambiguous assignment).

TL:DR; The purpose of init is provide initial values for all the properties, to create an instance in a consistent state