首页 > 解决方案 > 如何根据类类型返回对象?

问题描述

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

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

标签: iosswift

解决方案


它有一些解决方法:您需要创建一个协议,我们称之为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

备注:我将返回类型设置为 returnService而不是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

推荐阅读