From Apple's documentation:
The
@dynamicCallable
attribute lets you callnamed 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?
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With