Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is @dynamicCallable in Swift?

Tags:

ios

swift

swift5

From Apple's documentation:

The @dynamicCallable attribute lets you call named types like you call functions using a simple syntactic sugar. The primary use case is dynamic language interoperability.

Why would you want to use an @dynamicCallable instead of direct approch?

like image 964
Saranjith Avatar asked Mar 05 '23 06:03

Saranjith


1 Answers

@dynamicCallable is a new feature of Swift 5. From Paul Hudson's article on "How to use @dynamicCallable in Swift" (emphasis mine):

SE-0216 adds a new @dynamicCallable attribute to Swift, which brings with it the ability to mark a type as being directly callable. It’s syntactic sugar rather than any sort of compiler magic, effectively transforming this code:

let result = random(numberOfZeroes: 3)

Into this:

let result = random.dynamicallyCall(withKeywordArguments: ["numberOfZeroes": 3])

[...] @dynamicCallable is the natural extension of @dynamicMemberLookup [SE-0195], and serves the same purpose: to make it easier for Swift code to work alongside dynamic languages such as Python and JavaScript. [...] @dynamicCallable is really flexible about which data types its methods accept and return, allowing you to benefit from all of Swift’s type safety while still having some wriggle room for advanced usage.

like image 68
Anbu.Karthik Avatar answered Mar 11 '23 05:03

Anbu.Karthik