Skip to content

Instantly share code, notes, and snippets.

@harlanhaskins
Created March 5, 2018 22:09
Show Gist options
  • Save harlanhaskins/ebefee2aac501181438a97c8f91ec7a5 to your computer and use it in GitHub Desktop.
Save harlanhaskins/ebefee2aac501181438a97c8f91ec7a5 to your computer and use it in GitHub Desktop.
ScryfallAbstractionsExample
import Foundation
enum Result<Value> {
case success(Value)
case failure(Error)
func promote() throws -> Value {
switch self {
case .success(let value):
return value
case .failure(let error):
throw error
}
}
}
let scryfall = URL(string: "https://api.scryfall.com")!
/// Retreives JSON data from URL and parses it with JSON decoder. Thanks Mitchell
func parseResource<ResultType: Decodable>(call: String, completion: @escaping (Result<ResultType>) -> ()) {
let url = scryfall.appendingPathComponent(call)
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let content = data else {
print("Error: There was no data returned from JSON file.")
return
}
//print("\(String(data: content,encoding: .utf8))")
let decoder = JSONDecoder()
do {
// Decode JSON file starting from Response struct.
let decoded = try decoder.decode(ResultType.self, from: content)
completion(.success(decoded))
} catch {
// Known Issues:
// * Too broad of a request (needs handler)
//
// Present an alert if the JSON data cannot be decoded.
do {
let decoded = try decoder.decode(ScryfallError.self, from: content)
completion(.failure(decoded))
} catch {
completion(.failure(error))
}
return
}
}
task.resume()
}
struct Card: Codable {}
struct SomethingElse: Codable {}
parseResource(call: "cards/named") { (result: Result<Card>) in
}
func synchronouslyGetResource<T: Decodable>(call: String) throws -> T {
var result: Result<T>?
let semaphore = DispatchSemaphore(value: 0)
parseResource(call: call) { (res: Result<T>) in
result = res
semaphore.signal()
}
semaphore.wait()
return try result!.promote()
}
let fuck: Fuck = try synchronouslyGetResource(call: "something-else")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment