Skip to content

Instantly share code, notes, and snippets.

@ARamy23
Last active June 13, 2018 19:14
Show Gist options
  • Save ARamy23/95ba6640502bd4a3f618652c77c17149 to your computer and use it in GitHub Desktop.
Save ARamy23/95ba6640502bd4a3f618652c77c17149 to your computer and use it in GitHub Desktop.
//1
enum TodoRouter: URLRequestConvertible {
//2
static let baseURLString = "https://jsonplaceholder.typicode.com/"
//3
case get(Int)
case create([String: Any])
case delete(Int)
func asURLRequest() throws -> URLRequest {
var method: HTTPMethod {
switch self {
case .get:
return .get
case .create:
return .post
case .delete:
return .delete
}
}
//4
let params: ([String: Any]?) = {
switch self {
case .get, .delete:
return nil
case .create(let newTodo):
return (newTodo)
}
}()
//5
let url: URL = {
// build up and return the URL for each endpoint
let relativePath: String?
switch self {
case .get(let number):
relativePath = "todos/\(number)"
case .create:
relativePath = "todos"
case .delete(let number):
relativePath = "todos/\(number)"
}
//6
var url = URL(string: TodoRouter.baseURLString)!
if let relativePath = relativePath {
url = url.appendingPathComponent(relativePath)
}
return url
}()
//7
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = method.rawValue
//8
let encoding: ParameterEncoding = {
switch method {
case .get:
return URLEncoding.default
default:
return JSONEncoding.default
}
}()
return try encoding.encode(urlRequest, with: params)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment