I've created such wrapper. It makes code more concise. It indeed deals with Codable
, and should work fine with Firebase Coder as good as with any other one (such as JSONEncoder/Decoder). Let me modestly present
@CodableExcluded
import Foundation
@propertyWrapper
public struct CodableExcluded<Wrapped> {
public var wrappedValue: Wrapped?
public init(wrappedValue: Wrapped?) {
self.wrappedValue = wrappedValue
}
}
extension CodableExcluded: Encodable {
public func encode(to encoder: Encoder) throws {
// Do nothing. Actually this is never called due to empty `encode<Wrapped>` func in `KeyedEncodingContainer`
}
}
extension CodableExcluded: Decodable {
public init(from decoder: Decoder) throws {
self.wrappedValue = nil
}
}
extension KeyedDecodingContainer {
public func decode<Wrapped>(_ type: CodableExcluded<Wrapped>.Type, forKey key: Self.Key) throws -> CodableExcluded<Wrapped> {
CodableExcluded(wrappedValue: nil)
}
}
extension KeyedEncodingContainer {
public mutating func encode<Wrapped>(_ value: CodableExcluded<Wrapped>, forKey key: KeyedEncodingContainer<K>.Key) throws {
// Do nothing.
}
}
Usage
struct Test: Codable {
var codedString = "This will be included during encoding and decoded back."
@CodableExcluded var nonCodedString: String? = "This will NOT be included when encodig and assigned `nil` when decoded from decoded."
}
let data = try JSONEncoder().encode(Test())
print(String(data: data, encoding: .utf8) ?? "")
let obj = try JSONDecoder().decode(Test.self, from: data)
print(obj)