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 trialaaron du
5,946 Pointsinitializer code
I have a question about how to write initializers. in the videos, Pasan wrote an initializer like this
init(x: Int, y: Int){ self.position = Point(x: x, y: y) }
can someone break it down for me? Thanks
2 Answers
Michael Hulet
47,913 PointsAn initializer's job is to make sure every property (read: var
/let
at the class
/struct
scope) has a value. An initializer is just like every other method, but it's special because it gets called exactly once to set up a new object, and it also has special syntax because you don't have to write func
before it, and it will never declare a return
type (because the compiler knows it'll always return
a new instance of its class
/struct
or a subclass of it). In Pasan's example, he declares an initializer with the init
keyword. It takes 2 parameters: x
and y
, which are both Int
s. He then uses those values to give the property self.position
a new value of a Point
whose x
and y
values are equal to what's passed into the initializer. To illustrate this:
let newEnemy = Enemy(x: 1, y: 2)
print(newEnemy.location.x) // Prints 1
print(newEnemy.location.y) // Prints 2
let otherEnemy = Enemy(x: 57, y: 108)
print(otherEnemy.location.x) // Prints 57
print(otherEnemy.location.y) // Prints 108
Waylan Sands
Courses Plus Student 5,824 PointsI'm sure it will make more sense why we build classes this way. But now I'm wondering why a class isn't created like this. It would save all the inits, selfs, and supers.
class person(name: String, age: Int) { }
var newPerson = person(name: "John", age: 22)
class greatPerson(new prams): person(old prams) { }