Skip to content

Instantly share code, notes, and snippets.

@Pre1
Created June 18, 2016 19:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pre1/69ab8e8e2de0a78f1bc635ed5771b215 to your computer and use it in GitHub Desktop.
Save Pre1/69ab8e8e2de0a78f1bc635ed5771b215 to your computer and use it in GitHub Desktop.
from Swift Talk 1st episode
// Check out the talk: https://talk.objc.io/episodes/S01E01-networking (Part 1)
// the talk uses swift 2 and I follow along by writing it in swift 3.
import Foundation
import PlaygroundSupport
//extension Sequence {
// public func failingFlatMap<T>(_ transform: @noescape(Self.Iterator.Element) throws -> T?) rethrows -> [T]? {
// var result: [T] = []
// for element in self {
// guard let transformed = try transform(element) else { return nil }
// result.append(transformed)
// }
// return result
// }
//}
typealias JSONDictionary = [String: AnyObject]
struct Episode { let id, title: String }
extension Episode {
init?(dictionary: JSONDictionary) {
guard let id = dictionary["id"] as? String,
title = dictionary["title"] as? String
else { return nil }
self.id = id; self.title = title
}
}
struct Media {}
struct Resource<A> { let url: URL, parse: (Data) -> A? }
extension Resource {
init(_ url: URL, parseJSON: (AnyObject) -> A?) {
self.url = url
self.parse = { data in
let json = try? JSONSerialization.jsonObject(with: data)
return json.flatMap(parseJSON)
}
}
}
extension Episode {
static let all = Resource<[Episode]> (url) {
return ($0 as? [JSONDictionary])?.flatMap(Episode.init)
}
var media: Resource<Media> {
let url = URL(string: "http://localhost:8000/episodes/\(id).json")!
// TODO: Retuen the resource...
}
}
final class WebService {
func load<A>(resource: Resource<A>, completion: (A?) -> Void) {
URLSession.shared().dataTask(with: resource.url) { (data, _, _) in
completion(data.flatMap(resource.parse))
}.resume()
}
}
PlaygroundPage.current.needsIndefiniteExecution = true
WebService().load(resource: Episode.all) { print($0) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment