I've read couple tutorials, README from @mattt but can't figure out couple things.
What is the proper usage of URLRequestConvertible
in real world API? It looks like if I will create one router by implementing URLRequestConvertible
protocol for all API - it will be barely readable. Should I create one Router per endpoint?
Second question most likely caused by lack of experience with Swift language. I can't figure out why enum
is used for building router? Why we don't use class with static methods?
here is an example (from Alamofire's README)
enum Router: URLRequestConvertible {
static let baseURLString = "http://example.com"
static let perPage = 50
case Search(query: String, page: Int)
// MARK: URLRequestConvertible
var URLRequest: NSURLRequest {
let (path: String, parameters: [String: AnyObject]?) = {
switch self {
case .Search(let query, let page) where page > 1:
return ("/search", ["q": query, "offset": Router.perPage * page])
case .Search(let query, _):
return ("/search", ["q": query])
}
}()
let URL = NSURL(string: Router.baseURLString)!
let URLRequest = NSURLRequest(URL: URL.URLByAppendingPathComponent(path))
let encoding = Alamofire.ParameterEncoding.URL
return encoding.encode(URLRequest, parameters: parameters).0
}
}
There are 2 ways to pass parameters:
case CreateUser([String: AnyObject])
case ReadUser(String)
case UpdateUser(String, [String: AnyObject])
case DestroyUser(String)
and (say user has 4 parameters)
case CreateUser(String, String, String, String)
case ReadUser(String)
case UpdateUser(String, String, String, String, String)
case DestroyUser(String)
@mattt is using the first one in the example. But that will lead to "hardcoding" parameters' names outside the router (e.g. in UIViewControllers).
Typo in parameter name can lead to error.
Other people are using 2nd option, but in that case it not obvious at all what each parameter represents.
What will be the right way to do it?