Chapter    10

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 println and 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 empty () -> Bool {        return self.stack.count == 0    }

Get Learn Swift on the Mac: For OS X and iOS now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.