什么是使用扩展符合协议

我想知道扩展类和简单类之间的确切区别,以符合协议( 可读性除外)

假设我已经创build了类似tableview方法的类

class DemoVC:UIViewController,UITableViewDelegate,UITableViewDataSource { //MARK: - //MARK: - UITableview delegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { ... } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { ... } //Other codes } 

而不是如果我创build相同的类扩展来符合tableView方法

 extension DemoVC:UITableViewDelegate,UITableViewDataSource { //MARK: - //MARK: - UITableview delegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { .... } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } } 

那么哪个更好,为什么(except READABILITY)

第二个例子用double的扩展是好的

  extension Double { var mm: Double { return self / 1_000.0 } } let oneInch = 25.4.mm print("One inch is \(oneInch) meters") 

要么

 let oneInch = 25.4. / 1000 

所以在这里我的问题哪个更好使用双或者扩展我有简单的分裂双倍1000(如果我需要在特定类只)为什么?

扩展与Objective-C中的类别相似。 (与Objective-C类别不同,Swift扩展没有名称。)

扩展可以扩展现有types以使其采用一个或多个协议。 要添加协议一致性,您可以按照为类或结构编写协议名称的方式编写协议名称

 extension someClassName: OneProtocol, AnotherProtocol { // implementation of protocol requirements goes here } 

它的可读性和访问。 如果你在同一个类和文件中符合,实现对类的其他variables和函数的访问级别是不同的,而如果在不同的文件中定义它,它将具有不同的访问级别。

在下面的extension我们使用了inheritance的概念。

 extension DemoVC:UITableViewDelegate,UITableViewDataSource { //MARK: - //MARK: - UITableview delegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { .... } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } } 

而下面的extension是在一个类中增加了更多的function。

 extension Double { var mm: Double { return self / 1_000.0 } } let oneInch = 25.4.mm print("One inch is \(oneInch) meters") 

也可以在项目中的任何类中使用extension Double {} 。 意思就是我们必须调用一个方法,比如let oneInch = 25.4.mm

关于Swift 3,当你使用扩展时,你不能访问扩展类中的私有方法和结构。 所以如果你的数据模型是私有的,你不能通过扩展来访问它,如果你实现了表视图方法,你很可能会想要这样做。

关于Swift 4,唯一需要延长的时间就是你无法获得正在扩展的课程的来源。 在Swift 4中,私有数据可以通过在同一个文件中定义的扩展来访问,在这种情况下,任何一种方式都可以工作。

一个好的经验法则是:如果你有权访问类的源代码,并允许修改它,那么只需直接在类中遵守协议。 如果您没有源代码,或者您不允许修改源代码,那么您将需要使用扩展名。

除此之外,唯一的区别就在于可读性,正如你已经提到的那样,所以归结为一个风格问题,等待你的devise不需要访问私人数据。