CODEX

Swift—What Is a @dynamicCallable

Learn how to create Dynamic Callable types in Swift with examples.

Artturi Jalli
CodeX
Published in
3 min readMar 14, 2021

--

Photo by Sebastian Willius on Unsplash

Dynamic Callables in Swift

In Swift 5.0 and later there is a new way for calling a type by marking it @dynamicCallable.

When a type is a Dynamic Callable it means instead of this:

let greeter = Greeter()greeter.greet(name: "Nick")            // Prints "Hi, Nick."
greeter.greet(name: "Charles") // Prints "Hi, Charles."

You can do this:

let greeter = Greeter()greeter(someName: "Nick")               // Prints "Hi, Nick."
greeter(thisIsAlsoAName: "Charles") // Prints "Hi, Charles."

Or even this:

greeter(person1: "Thomas", name2: "Matt", whoever: "Tim")

If you didn’t catch it: Even thoughgreeter is an instance of a structure, you can call it like a function, with multiple arbitrary arguments.

Let’s see how this works and how easily you can create Dynamic Callables.

How to Create Dynamic Callables

Example 1

--

--

Artturi Jalli
CodeX
Writer for

Check @jalliartturi on YouTube to become a successful blogger. (For collabs, reach me out at: artturi@bloggersgoto.com)