gpt4 book ai didi

ios - 如何返回基于类类型的对象?

转载 作者:行者123 更新时间:2023-11-28 11:27:52 26 4
gpt4 key购买 nike

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

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

最佳答案

它有一些变通方法:您需要创建一个协议(protocol),我们称它为 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):

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

关于ios - 如何返回基于类类型的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57658608/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com