ios - 如何根据类类型返回对象?
问题描述
这是我出于测试目的需要的:
class AssemblerMock: Assemblerable {
func resolve<Service>(_ serviceType: Service.Type) -> Service? {
return Service.init() //doesnt work, need to return non nil value here.
}
}
解决方案
它有一些解决方法:您需要创建一个协议,我们称之为Initable
:
protocol Initable {
init()
}
那么,您的 resolve-Template-Method 应要求Service
为Initable
:
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
推荐阅读
- javascript - 如何在单页应用程序中触发 url 更改
- c - fgets() + sscanf() 如何写入大于其大小的数组?
- python - keras imagedatagenerator 不使用部分批处理
- postgresql-9.6 - centos7上如何删除postgresql9.6数据库?
- javascript - 在tomcat上部署spring boot应用程序时成功函数(javascript)的问题
- c# - 如何将扩展方法添加到自定义对象列表以将它们转换为新列表
- php - 本地主机:8000 不工作。它只是无限加载?
- javascript - AJAX POST 请求中的“未定义索引”错误,因为 $_POST 为空
- docker - 如何从现有 AMI 创建 docker 镜像
- javascript - 有没有办法在 React Js 中获取 Apache 环境变量?