• 20 hours
  • Medium

Free online content available in this course.

Videos available in this course

Certificate of achievement available at the end this course

Got it!

Last updated on 5/16/19

Define methods

Log in or subscribe for free to enjoy all this course has to offer!

We’ve learned how to create properties and initializers. What about methods?

Yeap..
Yeap..

We’ve done that already, because initializers are methods. They're just a special kind.

Can we create more methods?

We can create methods other than initializers. In fact, they are the essence of objects and must be taken advantage of.

What can they do?

Methods of a class can perform any action related to the context of an object.

Implementing methods

We already know that methods are functions declared in a class body:

class ClassName {
    func methodName() {
        // method logic
    }
}

Let's use Book class as an example. It could have a  read   method:

class Book {
    func read()
        // reading logic
    }
}

Just like regular functions, methods can have parameters and can return values.

In our Book example, we can have a more sophisticated read method that takes the number of pages to read as a parameter and returns the number of pages remaining to read:

class Book {
    func read(numberOfPages: Int) -> Int
        let totalPages = 10
        return totalPages - numberOfPages
    }
}

This will do, but it's far from perfect. Let's spice it up with properties :pirate::

  • totalPages - to store the number of pages of a book

  • currentPage - to store the number of pages read so far, so we can call our read method multiple times. 

class Book {
    //properties
    var totalPages: Int
    var currentPage: Int
    
    //initializers
    init(totalPages: Int) {
        self.totalPages = totalPages
        currentPage = 0
    }
    
    //methods
    func read(numberOfPages: Int) -> Int {
        currentPage += numberOfPages
        return totalPages - currentPage
    }
}

Done, can we move on?

We could move on, but there's a flaw in the logic of our method.

Have you figured it out >_<?

Sure you did. With this implementation we'll keep 'reading' pages beyond the total number of pages available :waw:. Let's quickly fix that by using a simple if statement:

func read(numberOfPages: Int) -> Int {
        currentPage += numberOfPages
        
        if (currentPage > totalPages) {
            currentPage = totalPages
        }
        
        return totalPages - currentPage
    }

Now done for real!

Calling methods on an object is very similar to accessing its properties by using the dot notation:

var myFavouriteBook = Book(totalPages: 700)
myFavouriteBook.read(numberOfPages: 100)

Pretty straightforward.

Back on the road - NeXTDestination

Let's look at our design:

NeXTDestination class design
NeXTDestination class design

We can spot a few methods:

  • Entertainment:

    • None 

  • Destination:

    • pickEntertainment

  • Adventure:

    • pickDestination

    • tellStory

You guessed it: it's your turn to practice! Create methods for our NeXTDestination classes. Let's limit it to declarations only. Here are some implementation tips:

  • When declaring pickEntertainment method, consider the following:

    • Implementation of the pickEntertainment method needs to consider the cost, therefore can use a parameter that specifies current state of a budget -  availableBudget 

    • Assuming the logic for for selecting the next option is implement, the result might be that nothing suitable is available. In this case the method needs to return nothing - nil. Time to remember Optionals!

  • When declaring pickDestination method, similarly to the entertainment context, consider the the case when no suitable option is available and the method must return nothing - nil

  • To make tellStory method more flexible, it's best to have the method return a story string string instead of printing it in place.

You are now all set to do it on your own!

I trust you finished your work before reaching this point!
I trust you have finished your work before reaching this point!

Let's review the results:

class Entertainment {
    /* no change */
}

class Destination {
    /* ... */

    //methods
    func pickEntertainment(availableBudget: Double) -> Entertainment? {
        return nil
    }
}

class Adventure {
    /* ... */

    // methods
    func pickDestination() -> Destination? {
        return nil
    }

    func tellStory() -> String {
        return ""
    }
}

Before we move on, let's list all the code in recollection:

class Entertainment {
    // properties
    var name: String
    var cost: Double

    // initializer
    init(name: String, cost: Double) {
        self.name = name
        self.cost = cost
    }
}

class Destination {
    // properties
    var name: String
    var cost: Double
    var entertainmentOptions: [Entertainment]
    var accomplishments: [Entertainment]
    
    // initializer
    init(name: String, cost: Double, entertainmentOptions: [Entertainment]) {
        self.name = name
        self.cost = cost
        self.entertainmentOptions = entertainmentOptions
        accomplishments = []
    }
    
    // methods
    func pickEntertainment(availableBudget: Double) -> Entertainment? {
        return nil
    }
}

class Adventure {
    // properties
    var amountSpent: Double
    var destinations: [Destination]
    var placesVisited: [Destination]
    
    // initializer
    init(destinations: [Destination]) {
        self.destinations = destinations
        amountSpent = 0.0
        placesVisited = []
    }
    
    // methods
    func pickDestination() -> Destination? {
        return nil
    }
    
    func tellStory() -> String {
        return ""
    }
}

Ok, we can move on now!

Let's Recap!

  • Methods are functions defined within the class

  • Methods can have parameters and return values

  • To call a method, use the dot notation - starting with the variable name and followed by the method name (providing the values for parameters where needed)

Example of certificate of achievement
Example of certificate of achievement