Chapter    12

Methods

A subroutine is a block of code that performs a specific task. Another name for a subroutine is a function. You’ve already seen global functions, such as print. Methods are functions that are associated with a particular type. In Swift, methods can be associated with classes, structures, and enumeration types. There are two types of methods: instance methods and type methods.

Instance Methods

Instance methods are those that belong to a particular instance of a class. You have to create an object to use those methods. They are defined just like standalone functions, but within the class scope:

class Stack {    private var stack = [Double]()    func isEmpty () -> Bool {        return self.stack.isEmpty    }    func peek () ...

Get Learn Swift 2 on the Mac, Second Edition 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.