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 Complex Data Structures Initializers and Self

Trevor Wood
Trevor Wood
17,828 Points

Swift OOP question about structure

So I was watching the video here. https://teamtreehouse.com/library/objectoriented-swift-20/complex-data-structures/initializers-and-self

And this code came up. I'm going to write some comments int there, please correct me if they're wrong or need improvement

struct Point{
    //create constant
    let x: Int
    let y: Int
    //give constant a value
    init(x: Int, y: Int){//gets values from "Point(x: 5, y: 1)"
        //self.x is the constant I created// self is targeting "Point" and the x inside
        // the x following self.x is the value I passed through.
        self.x = x
        self.y = y

Why would I choose to use this way over doing something like

func calculateArea(length: Int, width: Int) -> Int{
    let area = length * width
    return area

This way seems much less complicated and faster to read/write

3 Answers

With that function, the only thing you can do is call the function with a set of values. If for instance, you wanted to create and save a rectangle, your function wouldn't work. You could only call an area. If you wanted to create a variable or constant rectangle, then you use your struct (or class). I hope that explains it, if not let me know!

Trevor Wood
Trevor Wood
17,828 Points

Ah okay I see now what you mean. a Struct or Class can hold multiple data whereas a function can only execute and return code. Thanks!

No worries! Have fun learning Swift!

I dont think you can use dot notation with a function only a method