【发布时间】:2016-09-09 10:33:38
【问题描述】:
假设我有一个执行命令的Commander 对象。返回类型并不总是相同的,会根据命令而变化。
我希望能够使用将命令转发给指挥官的函数,测试结果是否属于某种类型(作为参数传递),然后在转换成功时调用成功闭包,以及否则失败关闭。
我尝试过像这样使用泛型参数:
func postCommand<T>(command: String, expectedResponseType: T, success: T -> Void, failure: (NSError?) -> Void) {
Commander.execute(command, completion: { (response: AnyObject?) in
guard let content = response as? T else {
failure(nil)
return
}
success(content)
})
}
这样称呼它
self.postCommand("command", expectedResponseType: [String: AnyObject], success: { (content: [String: AnyObject]) in
print("Success")
}) { (error: NSError?) in
print("Failure")
}
但是我从编译器得到一个错误:
Cannot convert value of type '([String : AnyObject]) -> Void' to expected argument type '_ -> Void'
如果我尝试这样做:
guard let content = response as? expectedResponseType
编译器抱怨expectedResponseType 不是一个类型。
我不知道该怎么做。有没有可能?
【问题讨论】: