Overloading Functions in Swift

Gabriel Theodoropoulos
5 min readAug 27, 2021
Photo by Murai .hr on Unsplash

Overloading functions or methods in Swift is a task that developers perform often. The technique that lies behind that term allows to create functions that have something in common; they share the same name, but there are certain rules to follow. Phrasing that in a more elegant way:

The definition of two or more functions or methods with the same name but different type of parameters, different number of parameters, or different argument labels, is what we call function overloading. Note that the return type plays no role at all.

Function overloading is particularly helpful in cases where the same or similar result or functionality is desirable under more than one circumstances. Think of the following example as a first taste; we could implement a function in order to fetch data from an SQLite database providing just the table name. But in addition to that, we could also implement another function accepting one more argument besides the table; a condition, based on which a where clause will limit retrieved data. Both these functions can have the same name, and given that they have different number of parameters, it’s perfectly acceptable to define them. Xcode won’t complain about them. Moreover, it will list them one after another in auto-suggestion while typing their name.

--

--

Gabriel Theodoropoulos
Gabriel Theodoropoulos

Written by Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev

No responses yet