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 Classes in Swift Instances of Classes

aren polat
aren polat
883 Points

init and class

I don't think i understood the init method right could someone give me explanation of what it does and why we need to use them. I watched the video a couple of times but i dont seem to understand it.

thank you

objects.swift
// Enter your code below

class Shape {
var numberOfSides: Int

init() {
self.numberOfSides = numberOfSides
}
}

let someShape = numberOfSides

1 Answer

So init is used to initialize the object i.e. assign it, its initial value. Below are two answers that are both accepted by the challenge. The first assigns a pre determined number of sides and the second uses a parameter in the init method which will be assigned later.

1 -

class Shape {
  var numberOfSides: Int

  init() {
    self.numberOfSides = 4
  }
}

let someShape = Shape()

2 -

class Shape {
  var numberOfSides: Int

  init(numberOfSides: Int) {
    self.numberOfSides = numberOfSides
  }
}

let someShape = Shape(numberOfSides: 4)