How to create an API like Alamofire does in Swift?

时间:2015-06-15 14:23:52

标签: ios swift alamofire

In the Alamofire.swift file the main API functions are not nested within a class or struct:

import Foundation
...
public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
    return Manager.sharedInstance.request(method, URLString, parameters: parameters, encoding: encoding)
}

yet they are able to be accessed as if they were a class func since Alamofire. is prepended to the function call:

Alamofire.request(.POST, "http://httpbin.org/post")

It doesn't appear to have anything to do with the fact the filename is Alamofire.swift. Is this a framework setting? I'd like to be able to do this for one of my own APIs

1 个答案:

答案 0 :(得分:1)

As described in the readme, Alamofire.request is used because you're importing the framework, so you have to specify where request is located.

When not using a framework, and importing the .swift files directly, it states:

Additionally, any of the calling conventions described in the 'Usage' section with the Alamofire prefix would instead omit it (for example, Alamofire.request becomes
request ), since this functionality is incorporated into the top-level namespace.

So to answer your question, to get your own API to use a prefix such as Alamofire, you need to create a framework an import it into your project.