我想使用枚举来包含泛型函数。这些枚举将作为参数传递,然后可以相应地执行枚举中的函数。在枚举中使用泛型函数
你如何设置在枚举定义,这样,他们将被视为功能泛型类型要执行?请注意,我有可能,我可能要通过各种函数定义。
让我知道,如果我在这儿可笑。 :)
// Define an enum to pass into my APIs. The S and F are meant to be functions I can define in anyway
enum FormattedResult<S, F> {
case Success(S)
case Failure(F)
func run<T> (a:T) {
switch (self){
case .Success (let completion):
// QN: How do I execute this? completion() will of course fail
debugPrint(completion)
case .Failure (let failure):
// QN: Same here
debugPrint(failure)
}
}
}
// I want to define a callback for someone else to call. I will be passing this to the error
var k1 = FormattedResult<(Int)->(), (String)->() >.Success(
{(a: Int) in
debugPrint("xxxxx")
})
// the APIClient can run this upon completion
k1.run(2)
// similarly for failures
var k2 = FormattedResult<(Int)->() , (String)->()>.Failure(
{(error: String) in
debugPrint(error)
}
)
k2.run("some error happened...")
'run(a:T)'方法中'T'的用途是什么? –
Kevin
因此调用者可以通过运行函数传递一个值来执行y。 –
运行功能应该采用“成功”定义的功能并运行T –