swift - 如何在 swift 中将特定类(符合约束)类型转换为泛型?

标签 swift generics casting

我的情况与以下与.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/

相关文章:

Java:如何创建通用 ENUM 类型

c++ - 为什么不使用 static_cast 的 const void* 类型转换在 C 而不是 C++ 中是合法的

c# - 使用在运行时定义类型的 'is'

c++ - 类型和未定义行为之间的指针转换

swift - 参数类型 'T.Type' 不符合预期类型 'Comparable'

c# - 如何通过反射找到重载的方法

ios - 在文本字段中快速添加逗号作为用户输入

ios - 为 swift 添加 Commoncrypto 文件后生成错误

ios - 如何将打印项目添加到 Firebase 数据库?

ios - 使用当前时间戳查询该时间之前的所有帖子