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 High Level Overview

Paige Stankevicius
Paige Stankevicius
1,761 Points

initialisers

So, I’m still trying to wrap my head around initialisers.

Whilst playing around with the code, i changed the ‘life’ property to a value of ‘Int' instead of giving it a value of 2 - but now i don’t know how to initialise it?

class Enemy {
    var life: Int
    let position: Point
    var strength: Int = 1

    init(x: Int, y: Int) {
    self.position = Point(x: x, y: y)
    }
} 

Also (with the code below), how come this shows up as an error (needing to be initialised), but if I change it from a class to a struct it doesn’t?

class hello {
var hi: String
}

1 Answer

Hi Paige,

Let me start by answering your second question... When it comes to initalizers, there is a major diff between a class and struct, that is struct comes normally with a built-in intializer, so if you dont create one , Swift creates one for you behind the scene. That why your code works when you made it a struct instead of class.

Now, going to your first question...To initialize the life value you have to that in the init method as following: init(x: Int, y: Int) { self.position = Point(x: x, y: y) self.life = 2
}

Paige Stankevicius
Paige Stankevicius
1,761 Points

Thank you, Safwat. I understand now.