Start a Project

@dynamicCallable in Swift

In this article, we will learn how to create Dynamic Callable types by the keyword @dynamicCallable in Swift.

There is a new way of calling a type using Dynamic Callables in Swift.

Let’s begin with the article.

Using @dynamicCallable in Swift

Let us understand the dynamic callables with the help of examples.

Create a struct named CallableExample as below.

Before @dynamicCallable Type, we call the function greetings as below.

Now, let’s re-create this CallableExample structure by making it a Dynamic Callable.

Here is how we can use the structure CallableExample.

By looking at the above code you will be able to infer the working of the Dynamic callables, however here is the explanation of the above code.

1. The CallableExample struct is marked as @dynamicCallable

2. The structure CallableExample is being used as a function.

3. In the CallableExample struct there is dynamicallyCall(withKeywordArguments:) method. This method is responsible for direct dynamic calls.

4. The dynamicallyCall method takes the KeyValuePairs as its arguments.

5. You can write your logic inside the dynamicallyCall method.

In addition, to the above example, we can also follow the below approach.

In the above code snippet, instead of passing the KeyValuePairs we are passing an array of String.

Notice the argument of dynamicallyCall method is different this time.

Conclusion

Dynamic Callable is helpful while working with other dynamic programming languages.

You can use any or both of the below functions while using Dynamic Callables in Swift.

dynamicallyCall(withKeywordArguments:)

dynamicallyCall(withArguments:)

For more info please check

If you want to read my other articles please click here.

Exit mobile version