Search code examples
swiftalamofireswift-protocols

Which request method in SessionManager is called when a type conforms to both URLRequestConvertible and URLConvertible?


This seems like more a Swift language question...

Say, I have a struct that conforms to both URLRequestConvertible and URLConvertible protocols:

struct Event {
    let title: String
}

extension Event: URLRequestConvertible {
}

extension Event: URLConvertible {
}

let anEvent = Event(title: "testing")

Alamofire.request(anEvent)

Which request method will be called?

In my test, the one with URLRequestConvertible as input argument (L156) is called.

Can you give me some pointers where this has been discussed among Swift language community? (I am not very sure about the computer science term for this kind of problem)


Solution

  • This is called method overloading in object oriented programming.

    Notice the call you make:

    Alamofire.request(anEvent)
    

    And the methods you have directed our attention to:

    public func request( //(1)
    _ url: URLConvertible,
    method: HTTPMethod = .get,
    parameters: Parameters? = nil,
    encoding: ParameterEncoding = URLEncoding.default,
    headers: HTTPHeaders? = nil)
    -> DataRequest
    
    public func request(_ urlRequest: URLRequestConvertible) -> DataRequest //(2)
    

    The call Alamofire.request(anEvent) will call the second function as it matches the method signature.

    You can learn about method overloading in almost any OOP learning material.