Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //: Playground - noun: a place where people can play
- enum APIRequest {
- case userLogin(username: String, password: String)
- case userLoginWithData(username: String, password: String)
- case addPromo(username: String, password: String, code: String)
- func getRawResponse(completion: @escaping ([String:Any]?, Error?) -> Void) {
- let dict = self.serialize()
- // session send dict
- // call completion
- }
- func serialize() -> [String: Any] {
- if case .userLogin(let username, let password) = self {
- return ["username": username, "password": password, "method": "p1"]
- }
- else if case .userLoginWithData(let username, let password) = self {
- return ["username": username, "password": password, "method": "p2"]
- }
- else {
- return [:]
- }
- }
- func getMappedResponse<T>(mapper: @escaping ([String:Any]) -> T?, completion: @escaping (T?, Error?) -> Void) {
- getRawResponse { (rawResponse, error) in
- if let error = error {
- completion(nil, error)
- return
- }
- guard let rawResponse = rawResponse else {
- completion(nil, error)
- return
- }
- if let mappedResponse = mapper(rawResponse) {
- completion(mappedResponse, nil)
- return
- }
- completion(nil, error)
- }
- }
- }
- // Usage:
- class UserModel {
- static func fromDictionary(_ dict: [String:Any]) -> UserModel {
- return UserModel()
- }
- }
- APIRequest.userLoginWithData(username: "test", password: "test").getMappedResponse(mapper: UserModel.fromDictionary) { (userModel, error) in
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement