没有额外投射的快速响应模板

时间:2017-09-09 20:07:24

标签: swift

有人知道如何在响应中实现模板但没有额外的投射?现在,如果我这样做,Xcode会返回错误,我无法动态覆盖T.但我真的相信我在正确的道路上却错过了一些东西。否?

现在看起来像是:func didReciveResponse(request: Request, response: Response<Any>)

    enum Response<T> {
        case success(response: T)
        case failured(error: Error)
    }

    func pseudoResponse() {
        let time: Timeinterval = 3
        // somehow cast T (compiler shows error that I can't do this)
        let response = .success<Timeinterval>(time)
        didReciveResponse(.time, response)
    }

    // delegate method
    func didReciveResponse(request: Request, response: Response) {
        switch request {
            case .time:
            switch response {
                // response without additional casting (as?)
                case .success(let value): time = value
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

由于编译器无法推断泛型类型,因此必须在此情况下注释类型

func pseudoResponse() {
    let time: TimeInterval = 3.0
    let response : Response<TimeInterval> = .success(response: time)
    didReciveResponse(request: .time, response: response)
}

,您必须在委托方法

中指定Response类型
func didReciveResponse(request: Request, response: Response<TimeInterval>) { ...

但是,如果你想使didReciveResponse(实际上didReceiveResponse)也是通用的,你需要写

func didReciveResponse<T>(request: Request, response: Response<T>) {