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

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

问题描述

我不明白程序员为什么在他们的类实现中使用 extension 关键字.您可以在其他主题中读到代码在语义上更加分离等等.但是当我使用自己的代码时,使用 //MARK - Something 对我来说感觉更清晰.那么当你在Xcode中使用methods list(ctrl+6)的时候,第一眼就看到了一切.

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."

那么为什么不直接在自己的类中编写自己的代码呢?不像我想扩展一些外部类的功能,比如 NSURLSessionDictionary,你必须使用扩展.

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 库中使用扩展,也许他可以给我一点解释,为什么他选择这种方法.

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天全站免登陆