Turning a function into a method

To explore methods and initializers, you will create a simple model for dates called SimpleDate. Be aware that Apple’s Foundation library contains a robust, production ready Date class that correctly handles all of the subtle intricacies of dealing with dates and times.

In the code below, how could you convert monthsUntilWinterBreak(date:) into a method?

let months = ["January", "February", "March",

"April", "May", "June",

"July", "August", "September", "October", "November", "December"]

struct SimpleDate {

var month: String

}

func monthsUntilWinterBreak(from date: SimpleDate) -> Int {

return months.index(of: "December")! - months.index(of: date.month)!

}

It’s as easy as moving the function inside the structure definition:

struct SimpleDate { var month: String

func monthsUntilWinterBreak(from date: SimpleDate) -> Int {

return months.index(of: "December")! - months.index(of: date.month)!

}

}

There’s no identifying keyword for a method; it really is just a function inside a named type. You call methods on an instance using dot syntax just as you do for properties. And just like properties, as soon as you start typing a method name, Xcode will provide suggestions. You can select one with the Up and Down arrow keys on your keyboard and you can autocomplete the call by pressing Tab:

let date = SimpleDate(month: "October")

let monthsLeft = date.monthsUntilWinterBreak(from: date) // 2

If you think about this code for a minute, you’ll realize that the method’s definition is awkward. There must be a way to access the content stored by the instance instead of passing the instance itself as a parameter to the method. It would be so much nicer to call this:

let monthsLeft = date.monthsUntilWinterBreak() // Error!

results matching ""

    No results matching ""