functions & methods

what’s the difference?

Vik Denic
vik denic

--

If you think methods in Swift look similar to functions, you’re right. In fact, they are functions.

But before discussing the difference between a function and a method in Swift, it helps to understand the difference between a stored variable and a stored variable property.

For example, consider the following variable named count :

Depending on the context, count can be either a stored variable, or a stored property. When a variable is declared at global scope or the local scope of a function, it is referred to as a stored variable. When it is declared in the context of a class or structure declaration, it is referred to as a stored variable property.

This same concept applies to functions and methods.

A method is simply a function that exists within a class. So every class inherits that method, whereas a function (declared outside of a class) can be called anywhere in the program.

For example, consider the following function:

What you see above is a function. It can be called anywhere in a program. But what if that function is declared within a class (shown below)?

Because func increment() is called within the class Counter, it is considered a method of that class. And is only called within instantiations of the Counter class.

Sources:

Apple Documentation on Declarations

Apple Documentation on Properties

StackOverflow

--

--