Last active
August 29, 2015 14:27
-
-
Save bgerstle/ca4ccd0c101e1f82ec91 to your computer and use it in GitHub Desktop.
Experimented with Swift generics after reading David Owens' post about protocols (http://owensd.io/2015/08/06/protocols.html)
This file contains hidden or 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 | |
public protocol UniversalResourceType { | |
var locator: NSURL { get } | |
} | |
public protocol HTTPResponseType : UniversalResourceType, Printable { } | |
public class HTTPResponse<T: Printable> : UniversalResourceType, Printable { | |
public var response: T | |
public var locator: NSURL | |
init(response: T, locator: NSURL) { | |
self.response = response | |
self.locator = locator | |
} | |
} | |
extension String : Printable { | |
public var description: String { get { return "\(self)" } } | |
} | |
extension HTTPResponse : Printable { | |
public var description: String { | |
get { | |
return "url: \(locator) response: \(response.description)" | |
} | |
} | |
} | |
typealias HTTPJSONResponse = HTTPResponse<NSObject> | |
typealias HTTPStringResponse = HTTPResponse<String> | |
let exampleJSON: NSObject = | |
NSJSONSerialization.JSONObjectWithData( | |
"{ \"foo\": \"bar\" }".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, | |
options: NSJSONReadingOptions.allZeros, | |
error: nil) as! NSObject | |
let jsonResponse = HTTPJSONResponse( | |
response: exampleJSON, | |
locator: NSURL(string: "https://foo.bar/biz")!) | |
let stringResponse = HTTPStringResponse(response: "foo", locator: NSURL(string: "https://foo.bar/baz")!) | |
let responses: [protocol<UniversalResourceType, Printable>] = [jsonResponse, stringResponse] | |
let responseDescriptions = responses.map() { "desc: \($0.description) url: \($0.locator)" } | |
println(responseDescriptions) | |
/* | |
[desc: url: https://foo.bar/biz response: { | |
foo = bar; | |
} url: https://foo.bar/biz, desc: url: https://foo.bar/baz response: foo url: https://foo.bar/baz] | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment