Skip to content

Instantly share code, notes, and snippets.

@kraigspear
Created November 16, 2020 13:51
Show Gist options
  • Save kraigspear/93c8dda50d1b97fdc3380b717df990b7 to your computer and use it in GitHub Desktop.
Save kraigspear/93c8dda50d1b97fdc3380b717df990b7 to your computer and use it in GitHub Desktop.
Providing the queue to call back on, default to main.
// Taken from https://www.swiftbysundell.com/clips/2/
extension Data {
func decoded<T: Decodable>(
as type: T.Type = T.self,
handledOn resultQueue: DispatchQueue = .main,
handler: @escaping (Result<T, Error>) -> Void
) {
let queue = DispatchQueue(label: "com.myapp.decoding")
let decoder = JSONDecoder()
queue.async {
let result = Result {
try decoder.decode(T.self, from: self)
}
resultQueue.async { handler(result) }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment