Skip to content

Instantly share code, notes, and snippets.

@uberbruns
Last active August 29, 2015 14:23
Show Gist options
  • Save uberbruns/2d13c9ce823a732bea8b to your computer and use it in GitHub Desktop.
Save uberbruns/2d13c9ce823a732bea8b to your computer and use it in GitHub Desktop.
A draft on how to use Protocol-Oriented Programming in Swift 2 with a web API
import UIKit
// We define a APIResultType as something that can be generated from a JSON
protocol APIResultType {
init?(json: String)
}
// A APIRequest is something that associates an URL with a APIResultType
protocol APIRequest {
typealias T: APIResultType
var url: String { get }
}
// We extend APIRequest with a function to load data from a webservice.
// Notice that the load method will init and return an APIResultType.
extension APIRequest {
private func loadJSON(url: String) -> String {
return "DATA FROM SERVER"
}
func load() -> T? {
let json = loadJSON(url)
return T(json: json)
}
}
// Now we want to make a music app, so we need a artist type
struct Artist {
var name: String
}
// First we make the artist type conform to the APIResultType so we can generate it from JSON
extension Artist : APIResultType {
init?(json: String) {
// Build self from data
// We use a failable initializer, because validation might fail
self.name = json
}
}
// To request an artist we create the ArtistRequest type that conforms to APIRequest
// and we associate this APIRequest with the Artist type.
// The ArtistRequest only needs an ID to make the URL for the request.
struct ArtistRequest : APIRequest {
typealias T = Artist
var id: Int
var url: String { return "http://api.mymusic.com/artists/\(id)" }
}
// To get an Artist type from the API we now only need to create a ArtistRequest,
// run it and we get the type we wanted.
if let artist = ArtistRequest(id: 123).load() {
print(artist.name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment