Last active
December 31, 2015 22:37
-
-
Save nunogoncalves/9519a876e9d373e41078 to your computer and use it in GitHub Desktop.
Creating multiple requesters with default behaviour using protocol extensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
protocol Getter { | |
typealias Element | |
func getUrl() -> String | |
func getDataFrom(dictionary: NSDictionary) -> Element | |
func get(success success: Element -> (), failure: () -> ()) | |
} | |
extension Getter { //Add default behaviour to Getter protocol. This behaviour depends on implementation of other protocol methods. | |
func get(success success: Element -> (), failure: () -> ()) { | |
let qos = Int(QOS_CLASS_USER_INTERACTIVE.rawValue) | |
dispatch_async(dispatch_get_global_queue(qos, 0)) { | |
let responseHandler = Data.HandleResponse() | |
responseHandler.failureCallback = { | |
dispatch_async(dispatch_get_main_queue()) { | |
failure() | |
} | |
} | |
responseHandler.successCallback = { dictionary in | |
let data = self.getDataFrom(dictionary) | |
dispatch_async(dispatch_get_main_queue()) { | |
success(data) | |
} | |
} | |
Network.Requester(networkResponseHandler: responseHandler).makeGet(self.getUrl()) //Class responsible to make the HTTP request. | |
} | |
} | |
} | |
struct Users { | |
class GetList: Getter { | |
private let searchOptions: SearchOptions | |
init(searchOptions: SearchOptions) { | |
self.searchOptions = searchOptions | |
} | |
func getUrl() -> String { | |
return "http://foobar.com/api/v0/users?\(searchOptions.urlEncodedOptions())" | |
} | |
func getDataFrom(dictionary: NSDictionary) -> [User] { | |
return ConvertUsersDictionaryToUsers(data: dictionary).users | |
} | |
} | |
} | |
struct Languages { | |
class Get: Getter { | |
func getUrl() -> String { | |
return "http://foobar.com/api/v0/languages" | |
} | |
func getDataFrom(dictionary: NSDictionary) -> [Language] { | |
return dictionary["languages"] as! [Language] | |
} | |
} | |
} | |
//Having a class within a struct is a way to create a "namespeced approach" which allows for a better code organization. We can have a namespace users, with multiple usecases: | |
Users.GetList, Users.GetOne, Users.Login, Users.Signup, this greatly improves readibility and organization. | |
//Usage: | |
Users.GetList().get(success: successCallback, failure: failureCallback); | |
Languages.Get().get(success: successCallback, failure: failureCallback); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment