问题
From Apple's documentation:
The
@dynamicCallableattribute lets you callnamed typeslike 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?
回答1:
@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
@dynamicCallableattribute 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])[...]
@dynamicCallableis 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. [...]@dynamicCallableis 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.
来源:https://stackoverflow.com/questions/55412536/what-is-dynamiccallable-in-swift