Skip to content

Instantly share code, notes, and snippets.

@mackoj
Created April 10, 2024 08:30
Show Gist options
  • Save mackoj/1e4b0836548ded323e08f6dcb8ea154e to your computer and use it in GitHub Desktop.
Save mackoj/1e4b0836548ded323e08f6dcb8ea154e to your computer and use it in GitHub Desktop.
Force AnyCodable to change a type of an object
import Foundation
import AnyCodable
// This is Fugly but it get the job done.
extension AnyCodable {
func transmuteThrow<Output: Codable>(_ encoder: JSONEncoder = JSONEncoder(), _ decoder: JSONDecoder = JSONDecoder()) throws -> Output {
let data = try encoder.encode(self)
return try decoder.decode(Output.self, from: data)
}
// obj.value.transmute(encoder, decoder) as [ThumbnailField]?
func transmute<Output: Codable>(_ encoder: JSONEncoder = JSONEncoder(), _ decoder: JSONDecoder = JSONDecoder()) -> Output? {
return try? transmuteThrow(encoder, decoder)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment