Avatar
@swift-5.4.3 protocol OptionalProtocol: ExpressibleByNilLiteral { associatedtype Wrapped static func some(_ value: Wrapped) -> Self static var none: Self { get } } extension OptionalProtocol { init(nilLiteral: Void) { self = .none } } extension Optional: OptionalProtocol {} struct APIResponse<Value>: Decodable where Value: Decodable { var value: Value? var error: APIResponseError? } extension APIResponse { func result() -> Result<Value, Error> { print("result") switch (value, error) { case (let value?, nil): return .success(value) case (nil, let error?): return .failure(error) case (_, _): return .failure(APIResponseError(code: -1)) } } } extension APIResponse where Value: OptionalProtocol { func result() -> Result<Value, Error> { print("result optional") switch (value, error) { case (let value?, nil): return .success(value) case (nil, let error?): return .failure(error) case (nil, nil): return .success(nil) case (_, _): return .failure(APIResponseError(code: -1)) } } } struct APIResponseError: Error, Decodable { var code: Int } struct User: Codable {} let r1: APIResponse<User> = .init(value: nil, error: nil) print(r1.result()) let r2: APIResponse<User?> = .init(value: nil, error: nil) print(r2.result())