If your iOS project uses Objective-C SDKs, you’ll find that the compiler does a good job of translating those APIs to Swift. Whenever you try to use one of them in Swift, you’ll be greeted with a Swiftified version of it that has common Objective-C standards translated to Swift. Foundation types like NSData and NSString will be translated to their Swift variants (Data, String), nullables will become optionals, and the name of the method will change to follow Swift's naming conventions. If the method can fail (by having an error pointer), it will even become a throwing function:

如果您的iOS项目使用Objective-C SDK,您会发现编译器将这些API转换为Swift的工作非常出色。 每当您尝试在Swift中使用其中之一时,都会看到它的Swiftized版本,该版本具有转换为Swift的通用Objective-C标准。 诸如NSDataNSString类的基础类型将转换为它们的Swift变体( DataString ), nullables将变为可选值,并且方法的名称将更改为遵循Swift的命名约定。 如果该方法可能失败(通过具有错误指针),则该方法甚至会变成抛出函数:

- (NSData *)dataForRow:(NSInteger)row error:(NSError **)error;// becomes:let data: Data = try data(for: row)

In most cases, this does the trick. While I’m not a fan of how the naming can end up sometimes, there are attributes that you can use to finetune the final result (e.g. NS_SWIFT_NAME(customName) to use a customized name or NS_SWIFT_NOTHROW to disable the error pointer -> throws conversion).

在大多数情况下,这可以解决问题。 虽然我不喜欢命名有时会如何结束,但是您可以使用一些属性来NS_SWIFT_NAME(customName)最终结果(例如NS_SWIFT_NAME(customName)以使用自定义名称,或NS_SWIFT_NOTHROW以禁用错误指针->引发转换)。

However, what if you want that Objective-C API to become something completely different? One example of a common architectural difference between the languages is the usage of methods versus properties. Most things in Objective-C are methods, while Swift will advise you to use computed properties for things that are computed but yet don’t involve actually processing data. The compiler isn’t that smart, so by default, you’ll end up with methods even if they are better defined as something else in Swift:

但是,如果您希望Objective-C API变成完全不同的东西怎么办? 语言之间常见的体系结构差异的一个示例是方法与属性的使用。 Objective-C中的大多数东西都是方法,而Swift会建议您将计算属性用于已计算但尚未实际处理数据的事物。 编译器不是那么聪明,因此默认情况下,即使在Swift中将它们更好地定义为其他方法,您也会得到方法:

MyClass.sharedInstance() // would work better in Swift as `MyClass.shared`!

Additionally, the automatic API translation doesn’t consider Swift-only features like default arguments and generics in methods — and those are really good tools for developing APIs in Swift. Fortunately, the compiler provides you with a way to completely customize how Objective-C APIs end up in Swift.

此外,自动API转换不考虑仅Swift的功能,例如方法中的默认参数和泛型-这些对于在Swift中开发API确实是很好的工具。 幸运的是,编译器为您提供了一种完全自定义Objective-C API在Swift中最终状态的方式。

NS_REFINED_FOR_SWIFT (NS_REFINED_FOR_SWIFT)

The NS_REFINED_FOR_SWIFT attribute can be added to Objective-C methods to indicate that you want to have full control of how this API is translated to Swift. When added to an Objective-C API, the compiler will still port it, but it will do so in the shape of a special hidden method that you can use to redefine it as something else. Here's an example of a singleton in Objective-C:

可以将NS_REFINED_FOR_SWIFT属性添加到Objective-C方法中,以指示您希望完全控制如何将此API转换为Swift。 当添加到Objective-C API时,编译器仍会移植它,但是它将以特殊的隐藏方法的形式进行移植,您可以使用该方法将其重新定义为其他名称。 这是Objective-C中一个单例的示例:

@interface SRMyClass : NSObject+ (instancetype)sharedInstance;@end

By default, this will be converted to a sharedInstance() method in Swift, but in Swift standards, this would look better as a computed property instead.

默认情况下,它将在Swift中转换为sharedInstance()方法,但是在Swift标准中,作为计算属性,它看起来会更好。

To customize how it’ll be translated, let’s add the attribute to the Objective-C definition:

为了自定义翻译方式,我们将属性添加到Objective-C定义中:

@interface SRMyClass : NSObject+ (instancetype)sharedInstance NS_REFINED_FOR_SWIFT;@end

As mentioned, using this attribute won’t stop the method from being migrated to Swift, but it’ll be done in a special way. In the case of methods, their name will be prefixed by two underscores (__):

如前所述,使用此属性不会阻止方法迁移到Swift,但是会以特殊方式完成。 对于方法,其名称将以两个下划线( __ )作为前缀:

let instance = SRMyClass.__sharedInstance()

The reason for this is precisely to indicate that this method shouldn’t be used as-is. In fact, if you try to implement this example, you’ll notice that while you can use it, it will not show in code completion at all. The intention, instead, is for you to abstract this special method into what you actually want this to look like in Swift. In the case of our singleton example, if we want it to become a computed property, we should define that property in our Swift code and implement it by calling the exposed unrefined method:

这样做的原因恰恰表明该方法不应原样使用。 实际上,如果您尝试实现此示例,则会注意到虽然可以使用它,但它完全不会显示在代码完成中。 相反,其目的是让您将此特殊方法抽象为您实际希望它在Swift中的外观。 在我们的单例示例中,如果我们希望它成为计算属性,则应该在Swift代码中定义该属性,并通过调用暴露的未精炼方法来实现该属性:

extension SRMyClass {    var shared: SRMySingleton {        return __sharedInstance()    }}

Because the original unrefined method doesn’t even show up in code completion, you can be sure that the developers will always use the correct Swiftified version of it.

由于原始的未优化方法甚至不会在代码完成中显示,因此可以确保开发人员将始终使用正确的Swiftized版本。

My personal favorite use of this attribute is to add default parameters to methods, which is something normally ignored in Objective-C for not being easy to implement but extremely simple and useful in Swift. To do so, we just need to create a version of the method that contains default parameters and internally call the original unrefined one:

我个人最喜欢使用此属性的方法是将默认参数添加到方法中,这在Objective-C中通常被忽略,因为它不易于实现,但在Swift中极其简单和有用。 为此,我们只需要创建一个包含默认参数的方法版本,并在内部调用原始的未优化的方法:

NS_REFINED_FOR_SWIFT is also a great way to enforce type safety in places where it wouldn't be applicable in Objective-C. In Swift, you can easily abstract unsafe id (Any/AnyObject) Objective-C methods (e.g. under generics).

NS_REFINED_FOR_SWIFT还是在Objective-C中不适用的地方强制执行类型安全的好方法。 在Swift中,您可以轻松地提取不安全的id ( Any / AnyObject )Objective-C方法(例如,泛型)。

public extension SRPersistance {    func object<T>(forKey key: String) -> T? {        return __object(forKey: key) as? T    }}

Unfortunately, you can’t redefine entire types with NS_REFINED_FOR_SWIFT, as only methods, properties, and initializers are supported. But in my experience, that's enough to give legacy code a good Swift experience.

不幸的是,您不能使用NS_REFINED_FOR_SWIFT重新定义整个类型,因为仅支持方法,属性和初始化程序。 但是以我的经验,这足以为遗留代码提供良好的Swift体验。

翻译自: https://medium.com/better-programming/adapting-objective-c-apis-to-swift-with-ns-refined-for-swift-fc66ca88ea51

http://www.taodudu.cc/news/show-4142877.html

相关文章:

  • 《Beyond Part Models: Person Retrieval with Refined Part Pooling 》PCB论文解读
  • 网易我的世界服务器配置文件翻译,精致存储的配置文件翻译 - [RS]精致存储 (Refined Storage) - MC百科|最大的Minecraft中文MOD百科...
  • 读论文Beyond Part Models Person Retrieval with Refined Part Pooling
  • Beyond Part Models: Person Retrieval with Refined Part Pooling (and A Strong Convolutional Baseline)
  • Beyond Part Models: Person Retrieval with Refined Part Pooling 阅读笔记
  • Feature Enhancement Network: A Refined Scene Text Detector
  • 差文解析 IIRC: Incremental Implicitly-Refined Classification
  • 《P2SGrad Refined Gradients for Optimizing Deep Face Models》论文阅读
  • Beyond Part Models: Person Retrieval with Refined Part Pooling (ECCV2018)
  • 论文阅读:RGCF: Refined Graph Convolution Collaborative Filering with Concise and Expressive Embedding
  • 序列标注 | (4) Hierarchically-Refined Label Attention Network for Sequence Labeling
  • RGCF: Refined Graph Convolution Collaborative Filering withConcise and Expressive Embedding
  • PCB:Beyond Part Models: Person Retrieval with Refined Part Pooling(论文阅读笔记)
  • R3Det: Refined Single-Stage Detector with Feature Refinementfor Rotating Object论文学习
  • 5.RefineDNet论文阅读
  • RefineDNet个人学习笔记
  • QQ等级加速
  • qq系统软件测试计划,软件测试设计报告案例——qq空间.doc
  • qq设置头衔显示服务器异常,qq头衔如何设置
  • 编程计算: 1!+3!+5!+...+(2n-1)!,要求阶乘计算调用fun函数实现, 数据输入及打印结果在主函数实现。阶乘计算fun函数原型为: long fun(int m); CQUPT题库
  • C语言求x的y次方,fun函数实现x的y次方的计算,main函数中调用fun函数
  • C语言编程>第十六周 ⑤ 请补充fun函数,该函数的功能是:依次取出字符串中所有大写字母,形成新的字符串,并取代原字符串。
  • C语言编程>第二十七周 ① 请补充fun函数,该函数的功能是:寻找两个整数之间的所有素数(包括这两个整数),把结果保存在数组a中,函数返回素数的个数。
  • C语言编程>第二十周 ③ 请补充fun函数,该函数的功能是:把字符串s中的字符按字符的ASCII码升序排列,处理后的字符串仍然保存在原串中,字符串及其长度作为函数参数传入。
  • C语言编程>第二十三周 ② 请补充fun函数,该函数的功能是:交换数组a中最大和最小两个元素的位置,结果重新保存在原数组中,其它元素位置不变。注意数组a中没有相同元素。
  • C语言编程>第二十七周 ③ 请补充fun函数,该函数的功能是计算并输出下列多项式的值:
  • C语言编程>第十六周 ④ 请补充fun函数,该函数的功能是将字符串str中的小写字母都改为对应的大写字母,其它字符不变。
  • C语言编程>第十七周 ⑤ 请补充fun函数,该函数的功能是:用来求出数组的最小元素在数组中的下标并存放在k所指的存储单元。
  • C语言编程>第二十二周 ⑧ 请补充fun函数,该函数的功能是:求100(不包括100)以内能被2或3整除,但不能同时被2和3整除的自然数。结果保存在数组a中,fun函数返回数组a元素的个数。
  • C语言编程>第二十四周 ① 请补充fun函数,该函数的功能是判断一个数是否为素数。该数是素数时,函数返回字符串 “yes!”,否则函数返回字符串 “no!”,并在主函数中输出。

使用NS_REFINED_FOR_SWIFT使Objective-C API适应Swift相关推荐

  1. 如何使php后端API跨域

    问题 ​ 今天在写一个后端api,通过get请求返回json.结果想试试效果,就在前端上用Vue.js写了请求.结果就直接报了错~ 错误提示如下:No 'Access-Control-Allow-Or ...

  2. 用 Swift、Foursquare API 和 Realm 創建一個咖啡屋 App

    原文链接 : Building a Coffee Shop App with Swift, Foursquare API and Realm 原文作者 : De Vries Reinder 译文出自 ...

  3. API经济时代,SWIFT推动银行业API接口标准化

    全球经济正在经历数字化转型,而数字化经济则基于数据的沟通和调用,在此背景下,能够让数据流通.应用集成更便捷.应用服务更安全的API(Application Programming Interface) ...

  4. [Swift]检查API可用性

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ ➤微信公众号:山青咏芝(shanqingyongzhi) ➤博客园地址:山青咏芝(https://www.cnblog ...

  5. 让 Objective-C 框架与 Swift 友好共存的秘籍

    Python实战社群 Java实战社群 长按识别下方二维码,按需求添加 扫码关注添加客服 进Python社群▲ 扫码关注添加客服 进Java社群▲ 作者:江湖人称 "七叔" 其实就 ...

  6. Swift 周报 第二十九期

    文章目录 前言 新闻和社区 担心泄密!外媒:苹果公司限制员工使用ChatGPT 苹果公司大幅削减其MR头显销售预期,不足百万台 提案 通过的提案 正在审查的提案 Swift 论坛 1.讨论 Swift ...

  7. Swift教程之控制流

    控制流 Swift包含很多控制流语句:while循环.if.guard.switch和for-in循环. For-In循环 for-in循环用于迭代序列,如数组遍历.数字范围.字符串中的字符. 下面为 ...

  8. Swift傻傻分不清楚系列(七)控制流

    本页包含内容: For-In 循环 While 循环 条件语句 控制转移语句(Control Transfer Statements) 提前退出 检测 API 可用性 Swift提供了多种流程控制结构 ...

  9. 如何使用Instruments诊断App(Swift版):起步

    2019独角兽企业重金招聘Python工程师标准>>> 本文由Mr_cyz(博客)翻译自raywenderlich,欢迎参与我们的翻译活动. 原文:Instruments Tutor ...

  10. 在Swift中使用C语言的指针

    点击上方蓝字关注我,了解更多咨询 Objective-C和C语言经常需要使用到指针.Swift中的数据类型由于良好的设计,使其可以和基于指针的C语言API无缝混用.同时 Swift也可以自动处理大多数 ...

最新文章

  1. Go 知识点(01)— 主协程与子协程执行顺序
  2. git init 会不会清空_Git命令:git pull amp; git fetch
  3. 刘光瑞php,PHP Markdown 解析器 HyperDown
  4. poj2449(第k短路)
  5. python 批量读取文件夹的动漫美女图并显示
  6. disk genius_如何预约Apple Store商店或Genius Bar
  7. 并发模式之Future模式
  8. 一起学java【5】---原生态数据类型使用陷阱
  9. win10右下角的天气怎么关闭
  10. 2021年《初级会计实务》考试真题资产部分
  11. 2022年全球市场木材干燥窑总体规模、主要生产商、主要地区、产品和应用细分研究报告
  12. 上海驾驶证满6年换证
  13. Java快递配送管理系统
  14. 一款自制calendar插件
  15. 「经济读物」小狗钱钱
  16. 网络原理——TCP协议
  17. html粘贴excel表格大小不一样,为什么excel表格粘贴的时候显示因为单元格形状大小不一样无法粘贴呢...
  18. Substance Painter 服饰材质制作 - 肩带1
  19. ffmpeg音视频处理
  20. python如何精确过滤出一个串里的英文单词

热门文章

  1. 基于深度学习的图像压缩
  2. python土味情话_GitHub - MMstarry/itchat: 微信机器人 土味情话
  3. oracle异构mysql_Oracle GoldenGate学习之--异构平台同步(Mysql到Oracle)
  4. 后端开发java与php,【后端开发】java与php的区别是什么
  5. 后端开发发展学习路线
  6. HBuilder的mui登录模板修改登录页为非入口页面的方法
  7. 【07月09日】预分红股息率最高排名
  8. zkw线段树(详解)
  9. 递归求解问题hdu2044一只小蜜蜂...
  10. NLP task2 N-Gram