Swift - 一种方法 2 类

Swift - one method 2 classes

如何在 Swift 中将一种方法应用于 2 个不同的 classes?

class Class1 {
      func doSomething() {
        self.doSomethingOnClass()
      }
}

   class Class2 {
      func doSomething() {
        self.doSomethingOnClass()
      }
}

所以基本上我想做的不是在每个 class 上实现相同的方法我想提取方法然后要求它将自己视为 Class1 或 Class2。我希望协议可以做到,但看起来如果 class 实现协议,那么无论如何我都必须为每个 class 编写实现。 有什么建议可以实现这一目标的最佳做法是什么?或者最好是在 class 中实现它,即使这意味着重复代码。

基本上有两种方法可以做到这一点:继承或协议。 Swift肯定倾向于后者,如果只涉及一个功能,继承肯定是一个糟糕的选择。

以下是使用协议完成此操作的方法:

protocol CommonFunc: class {
    func doSomethingOnClass()
}

extension CommonFunc {
    func doSomethingOnClass() {
        print(type(of: self))
    }
}

class A: CommonFunc {

}

class B: CommonFunc {

}

A().doSomethingOnClass() // A
B().doSomethingOnClass() // B

这可以使用协议和扩展来完成。这是使用 Playgrounds 制作的示例。如果愿意,您可以将此代码复制并粘贴到 playground 中进行修改,请注意扩展协议为 类 和类似结构提供了默认实现。

//: Playground - noun: a place where people can play

import UIKit

protocol ClassProtocol {
    func classMethod()
}

extension ClassProtocol {
    func classMethod() {
        print("here i am")
    }
}

class Class1: ClassProtocol { }

class Class2: ClassProtocol { }

struct Struct1: ClassProtocol { }

Class1().classMethod()
Class2().classMethod()
Struct1().classMethod()

输出:

here i am
here i am
here i am

这里发生了什么?该协议定义了使用该协议的任何对象或结构都需要方法 classMethod。然后扩展为该方法提供默认实现。如有必要,您也可以覆盖此默认实现。

struct Struct2: ClassProtocol {
    func classMethod() {
        print("this does something different")
    }
}

Struct2().classMethod()

输出:

this does something different