Created
April 10, 2024 08:30
-
-
Save mackoj/1e4b0836548ded323e08f6dcb8ea154e to your computer and use it in GitHub Desktop.
Force AnyCodable to change a type of an object
This file contains 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 | |
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