Skip to content

Instantly share code, notes, and snippets.

@rb-de0
Last active March 26, 2016 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rb-de0/bd228eecf1ad4138b823 to your computer and use it in GitHub Desktop.
Save rb-de0/bd228eecf1ad4138b823 to your computer and use it in GitHub Desktop.
protocol XMLDecodable{}
protocol JSONDecodable{
associatedtype DecodedType = Self
}
protocol RequestType{
associatedtype ResponseType
var root: String{ get }
var endpoint: String{ get }
var method: String{ get }
var timeoutInterval: Int{ get }
func header() -> [String: String]
func parameter() -> [String: AnyObject]
}
extension RequestType where ResponseType: XMLDecodable{
var timeoutInterval: Int{
return 10
}
func header() -> [String: String]{
return ["Content-Type": "application/x-www-form-urlencoded"]
}
func responseFromXml() -> String{
API.sendRequest(self){print($0)}
return "xml"
}
}
extension RequestType where ResponseType: JSONDecodable, ResponseType.DecodedType == ResponseType{
var timeoutInterval: Int{
return 5
}
func header() -> [String: String]{
return ["Content-Type": "application/json"]
}
func responseFromJson() -> String{
API.sendRequest(self){print($0)}
return "json"
}
}
struct XMLResponse: XMLDecodable{}
struct JSONResponse: JSONDecodable{}
struct API {
static func sendRequest<T: RequestType>(request: T, completion: (T.ResponseType -> Void)?){
}
}
struct JSONRequest: RequestType{
typealias ResponseType = JSONResponse
let root = ""
let endpoint = ""
let method = "GET"
func parameter() -> [String : AnyObject] {
return [:]
}
}
struct XMLRequest: RequestType{
typealias ResponseType = XMLResponse
let root = ""
let endpoint = ""
let method = "GET"
func parameter() -> [String : AnyObject] {
return [:]
}
}
let jsonRequest = JSONRequest()
jsonRequest.header() // -> ["Content-Type": "application/json"]
jsonRequest.responseFromJson() // -> "json"
print(jsonRequest.timeoutInterval) // -> 5
let xmlRequest = XMLRequest()
xmlRequest.header() // -> ["Content-Type": "application/x-www-form-urlencoded"]
xmlRequest.responseFromXml() // -> "xml"
print(xmlRequest.timeoutInterval) // -> 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment