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 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.