从泛型类的扩展/泛型类方法分派中调用函数

时间:2018-07-10 10:57:52

标签: swift generics extension-methods

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

protocol ModuleConfigurator {
    func execute()
}
protocol ModuleProperties { }

class BackupCardProperties { }
extension BackupCardProperties: ModuleProperties { }
class IntroductionProperties { }
extension IntroductionProperties: ModuleProperties { }


class Configurator<T> where T: ModuleProperties {

    // MARK: - Properties

    var properties: T

    // MARK: - Initialization

    init(properties: T) {
        self.properties = properties
    }
}
extension Configurator: ModuleConfigurator {
    func execute() {
        print("Configurator")
    }
}

extension Configurator where T == IntroductionProperties {
    func execute() {
        print("IntroductionProperties")
    }
}

extension Configurator where T == BackupCardProperties {
    func execute() {
        print("BackupCardProperties")
    }
}

var list: [ModuleConfigurator] = [Configurator<BackupCardProperties>(properties: BackupCardProperties()),
                                  Configurator<IntroductionProperties>(properties: IntroductionProperties())]

list.forEach { config in
    config.execute()
}
  

配置器   配置器

是否有可能实现

  

BackupCardProperties   简介属性

编辑

无协议

protocol ModuleConfigurator {
    func execute()
}
protocol ModuleProperties { }

class BackupCardProperties { }
extension BackupCardProperties: ModuleProperties { }
class IntroductionProperties { }
extension IntroductionProperties: ModuleProperties { }


class Configurator<T> where T: ModuleProperties {

    // MARK: - Properties

    var properties: T

    // MARK: - Initialization

    init(properties: T) {
        self.properties = properties
    }
}
extension Configurator where T == IntroductionProperties {
    func execute() {
        print("IntroductionProperties")
    }
}

extension Configurator where T == BackupCardProperties {
    func execute() {
        print("BackupCardProperties")
    }
}
Configurator<BackupCardProperties>(properties: BackupCardProperties()).execute()

0 个答案:

没有答案