我的情况与以下与.Net相关的问题类似。
Value of type 'T' cannot be converted to TServiceResponse 是 我的代码:
public class TServiceResponse : ResponseNode,CommsObject{
public var type : String!
public var Status : String?
required public init?(_ dictionary: NSDictionary){
self.type = dictionary.field("$type")
self.Status = dictionary.field("Status")
}
}
public enum WebResult<T : ResponseNode> {
case Result(JsonResponse<T>)
case Error(NSError)
}
func executePost<Message : RequestMessage, Node : ResponseNode>(request: JsonPostRequest<Message>,
completionHandler: (result: WebResult<Node>) -> Void) -> NSURLSessionTask?{
if let jsonResponse : JsonResponse<TServiceResponse> = self.createResponse(data, error: &runtimeError){
return completionHandler(result: (jsonResponse as? WebResult<Node>)!)
}
}
我相信我的要求首先就违背了泛型的目的。但是有没有办法可以完成这个任务呢?我需要这个 hack 来确保我对代码进行最少的更改。
最佳答案
这应该有效:
let result = runtimeError.code == 0 ? WebResult.Result(jsonResponse) : WebResult.Error(runtimeError)
return completionHandler(result:result)
关于swift - 如何在 swift 中将特定类(符合约束)类型转换为泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34945065/