【发布时间】:2016-03-03 01:07:03
【问题描述】:
我正在尝试使用枚举来包含通用函数。这些枚举将作为参数传递,然后可以相应地执行枚举中的函数。
您将如何在枚举定义中设置泛型类型,以便将它们识别为要执行的函数?请注意,我可能有各种想要传入的函数定义。
如果我在这里很可笑,请告诉我。 :)
// 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...")
【问题讨论】:
-
T在run<T> (a: T)方法中的作用是什么? -
所以调用者可以传入一个值,由run函数执行。
-
运行函数应该是把"success"定义的函数用T运行