如何基于类类型返回对象?

时间:2019-08-26 13:12:30

标签: ios swift

这是我出于测试目的所需要的:

class AssemblerMock: Assemblerable {
    func resolve<Service>(_ serviceType: Service.Type) -> Service? {
        return Service.init() //doesnt work, need to return non nil value here.
    }
}

1 个答案:

答案 0 :(得分:2)

它有一些解决方法:您需要创建一个协议,我们将其称为Initable

protocol Initable {
    init()
}

然后,您的resolve-Template-Method应该要求ServiceInitable

func resolve<Service>(_ serviceType: Service.Type) -> Service where Service:Initable {
    return Service.init()
}

使用它之前,您还需要为所有可能要解析的类型创建一个扩展名:

extension Int : Initable {
    // No implementation possible/needed, because `init` already exits in struct Int
} 

然后命名:

let am = AssemblerMock()
let i = am.resolve(Int.self)
print (i)   // Prints "0" because this is the default Integer value

备注:我将返回类型设置为返回Service而不返回Service?,但是这里没有关系。如果要支持失败的初始化程序(init?),则需要修改返回类型以及Initable协议:

protocol Initable {
    init?()
}

extension Int : Initable {} 

class FooFailing : Initable {
    required init?() {
        return nil
    }
}

class AssemblerMock {
    func resolve<Service>(_ serviceType: Service.Type) -> Service? where Service:Initable {
        return Service.init()
    }
}

let am = AssemblerMock()
let i = am.resolve(Int.self)
print (i)   // Optional(0)
let foo = am.resolve(FooFailing.self)
print (foo) // nil