Swift和使用类扩展 [英] Swift and using class extension

查看:210
本文介绍了Swift和使用类扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么程序员在他们的类实现中使用 extension 关键字。你可以阅读其他主题的代码然后更多语义分离等等。但是当我使用自己的代码,使我感觉更清楚使用 // MARK - Something

I don't understand why programmers use the extension keyword in their class implementation. You can read in other topics that code is then more semantically separated and etc. But when I work with my own code, it feels clearer to me to use // MARK - Something. Then when you use methods list (ctrl+6) in Xcode, everything is seen at first look.

在Apple文档中,你可以看到:

In Apple documentation you can read:


扩展为现有类,结构或枚举类型添加新功能。

"Extensions add new functionality to an existing class, structure, or enumeration type."

那么为什么不直接在我自己的类里面写我自己的代码?不像我想扩展一些外部类的功能,比如 NSURLSession Dictionary ,其中来使用扩展。

So why not write my own code directly inside my own class? Unlike when I want to extend functionality of some foreign class, like NSURLSession or Dictionary, where you have to use extensions.

Mattt Thompson在他的Alamofire库中使用扩展名,也许他可以给我一点解释, b $ b

Mattt Thompson use extension in his Alamofire library, maybe he can give me little explanation, why he chose this approach.

推荐答案

对我来说,这似乎是完全合理的,因为你可以使用扩展来暴露不同的逻辑部分到不同的扩展。这也可以用于使类符合协议更可读,例如

For me it seems completely reasonable since you can use extensions to expose different parts of logic to different extensions. This can also be used to make class conformance to protocols more readable, for instance

class ViewController: UIViewController {
...
}

extension ViewController: UITableViewDelegate {
...
}

extension ViewController: UITableViewDataSource {
...
}

extension ViewController: UITextFieldDelegate {
...
}

为了清楚起见,协议方法在不同的扩展名中分开,这看起来比读者要好得多:

Protocol methods are separated in different extensions for clarity, this seems to be far better to read than lets say:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {}

我想说,使用扩展没有任何危害,使自己的代码更可读,而不只是扩展已经存在的类从SDK。使用扩展可以避免在控制器中有大量的代码,并且将功能拆分为易于阅读的部分,因此使用扩展没有任何缺点。

So, I'd say there's no harm in using extensions to make your own code more readable, not just to extend already existing classes from SDK. Using extensions you can avoid having huge chunks of code in your controllers and split functionality into easily readable parts, so there's no disadvantage of using those.

这篇关于Swift和使用类扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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