There's no safe way to simply cast between two unrelated types that I'm aware of, and Container<A>
and Container<B>
are unrelated alright.
It's also worth mentioning that you can define a custom decode(_:forKey:)
function which will be picked up by the synthesizer. It should give you enough leeway to ignore/redirect the key. This technique can be gleaned from ResilientDecoding. Note that the wrapper still needs to conform to Decoder
. As an example, the following code uses our custom decode
function:
import Foundation
@propertyWrapper
struct TestWrap<T: ExpressibleByIntegerLiteral>: Decodable {
var wrappedValue: T
init(from decoder: Decoder) throws { fatalError() }
init() { wrappedValue = 3 }
}
extension KeyedDecodingContainer {
func decode<T>(_: TestWrap<T>.Type, forKey: Key) -> TestWrap<T> {
.init()
}
}
struct Test: Decodable {
@TestWrap var a: Int
}
let raw = #"{}"#, decoder = JSONDecoder()
let result = try decoder.decode(Test.self, from: .init(raw.utf8))
print(result.a) // 3
Try not to use this trick too much, though. It can be tricky to reason with.