Defining Methods in Structs

When we say methods, we are talking about the functions within structs. Methods are just functions that are going to be associated with the structs. By defining a method within the curly brackets of a struct, you are saying that this function belongs to this struct.

Here’s an example of a struct with Point, Size, and Rect, which will based on CGRect:

struct Point {    var x:Int, y:Int}struct Size {    var width:Int, height:Int}struct Rect {    var origin:Point, size:Size    func center() -> Point {        var x = origin.x + size.width/2        var y = origin.y + size.height/2        return Point(x: x, y: y)    }}

The first thing to note is that you declared all the variables on one line. ...

Get Learning Swift™ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.