Swift 中的 @dynamicCallable 是什么? [英] What is @dynamicCallable in Swift?

查看:36
本文介绍了Swift 中的 @dynamicCallable 是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Apple 的文档:

From Apple's documentation:

@dynamicCallable 属性让你可以像调用一样调用 named types函数使用简单的语法糖.主要用例是动态语言互操作性.

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.

为什么要使用 @dynamicCallable 而不是直接方法?

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

推荐答案

@dynamicCallable 是 Swift 5 的一个新特性.来自 Paul Hudson 关于如何在 Swift 中使用 @dynamicCallable"的文章(重点是我的):

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

SE-0216 补充说一个新的 @dynamicCallable 属性 给 Swift,它它带来了将类型标记为可直接调用的能力.这是语法糖,而不是任何编译器魔法,有效地转换此代码:

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)

进入这个:

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

[...] @dynamicCallable@dynamicMemberLookup [SE-0195],并用于相同的目的:让 Swift 代码更容易与动态语言一起工作,例如作为 Python 和 JavaScript.[...] @dynamicCallable 对于哪些数据非常灵活输入它的方法接受和返回,让你受益于所有Swift 的类型安全性,同时仍有一些回旋余地高级用法.

[...] @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.

这篇关于Swift 中的 @dynamicCallable 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆