Updated 31 January 2023
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.
Let us understand the dynamic callables with the help of examples.
Create a struct named CallableExample as below.
1 2 3 4 5 |
struct CallableExample{ func greetings(name: String) { print("Hello!",name) } } |
Before @dynamicCallable Type, we call the function greetings as below.
1 2 |
let greeting = CallableExample() greeting.greetings(name: "Hello") |
Now, let’s re-create this CallableExample structure by making it a Dynamic Callable.
1 2 3 4 5 6 7 8 9 |
@dynamicCallable struct CallableExample { func dynamicallyCall(withKeywordArguments args: KeyValuePairs<String, String>) { // your logic here for (_, value) in args { print("Hello!",value) } } } |
Here is how we can use the structure CallableExample.
1 2 3 |
let greeting = CallableExample() greeting(someValue: "How are you?") // output- "Hello!How are you?" greeting(anotherValue: "I am fine") // output- "Hello!I am fine" |
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.
1 2 3 4 5 6 |
@dynamicCallable struct CallableExample { func dynamicallyCall(withArguments args: [String]) { //your logic here } } |
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.
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.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.