1

I have a struct like this

struct ApiResponse<T: Codable>: Codable {
 let result: T?
 let statusCode: String?
}

Somewhere in my code I need statusCode. I am not interested in result but Swift is not allowing me to use following:

let apiResponse = value as? ApiResponse

it shows following error:

Generic parameter 'T' could not be inferred in cast to 'ApiResponse'

which is quite obvious since struct definition ask some struct conforming to Codable but at same time i can not use one type as it will fail for other types.

e.g.

let apiResponse = value as? ApiResponse<ApiResult> 

would be true for one type of response but if i have ApiResponse<ApiOtherResult> it will fail.

        NetworkLayer.requestObject(router: router) { (result: NetworkResult<T>) in

        switch result {
        case .success(let value):
            if let apiResponse = value as? ApiResponse {
                }
        case .failure: break
        }

    }
Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
Arslan Asim
  • 1,232
  • 1
  • 11
  • 29

1 Answers1

1

I'd suggest adding a new protocol

protocol StatusCodeProvider {
    var statusCode: String? { get }
}

Add it as a requirement in your function making sure that T in NetworkResult<T> conforms to StatusCodeProvider and add conformance for every T you want to request.

RTasche
  • 2,614
  • 1
  • 15
  • 19