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 Introduction to Structs

Ryan Maneo
Ryan Maneo
4,342 Points

Couldn't the same thing be done with a func?

For this structure:

struct Point { // structures have UpperCamelCase let x: Int let y: Int }

I made a func: func point2(x x: Int, y: Int) -> (Int, Int) { return (x, y) }

both appear to have the exact same use. Is one better than the other?

To make your code more readable in the forum use 3 backticks on the line before and after code. The backtick is just above the tab key on a mac.

Using the 3 backticks one line above and one line below your code will make it more readable. Refer to the Mardown Cheatsheet.

The structure:

struct Point { // structures have UpperCamelCase
    let x: Int
    let y: Int
}

And your function:

func point2(x x: Int, y: Int) -> (Int, Int) {
   return (x, y)
}

1 Answer

Structures not only let us store properties but also methods (functions associated with them). Try the following example (taken from Apple, refer to The Swift Programming Language for details).

struct Point {
    var x = 0.0, y = 0.0
    func isToTheRightOfX(x: Double) -> Bool {
        return self.x > x
    }
}
let somePoint = Point(x: 4.0, y: 5.0)
if somePoint.isToTheRightOfX(1.0) {
    print("This point is to the right of the line where x == 1.0")
}
// Prints "This point is to the right of the line where x == 1.0"