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

Ken Okiebisu
Ken Okiebisu
9,673 Points

Swift:Instances of Classes

I tried writing down the codes but because I am don't fully understand initializers, I'm pretty stuck right now. Can someone show me how to solve this problem?

objects.swift
// Enter your code below
class Shape {
var numberOfSides: Int
init (numberOfSides: Int) {
self.numberOfSides = numberOfSides
}
}
let someShape = Shape()

2 Answers

Ryan Maneo
Ryan Maneo
4,342 Points

Hello, in this case, all you need to do is give an initial value to numberOfSides, like this:

class Shape {
  var numberOfSides: Int = 1
}

let someShape = Shape()

What you did would have worked as well, however, this specific code challenge requires the initial value be set to the variable directly.

Ken Okiebisu
Ken Okiebisu
9,673 Points

Thank you! It worked! You mentioned that initial value can be set to the variable directly and does that mean that we don't have to write init for every classes but set variables directly?

Ryan Maneo
Ryan Maneo
4,342 Points

Hello, it depends on the issue, If you wanted to have something that could take no value at all, then you would use an init method, rather than adding it directly. Since this is a Shape class, it must have at least 1 side, therefore a value set to the variable itself works out in this case.

Ken Okiebisu
Ken Okiebisu
9,673 Points

Thank you! Now I got it!