What is @dynamicCallable in Swift?

只愿长相守 提交于 2019-12-08 11:29:42

问题


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?


回答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 @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.



来源:https://stackoverflow.com/questions/55412536/what-is-dynamiccallable-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!