Skip to content

Instantly share code, notes, and snippets.

@mackoj
Created June 3, 2022 21:03
Show Gist options
  • Save mackoj/23349e6ba386cafc70eea67aff18be8d to your computer and use it in GitHub Desktop.
Save mackoj/23349e6ba386cafc70eea67aff18be8d to your computer and use it in GitHub Desktop.
This PropertyWrapper allow a property to not be encoded with Codable without needed to create a custom CodingKeys.
import Foundation
/// This allow a property to no be encoded
@propertyWrapper
public struct NotCodable<Boxed> {
private var value: Boxed?
public init(wrappedValue: Boxed?) {
self.value = wrappedValue
}
public var wrappedValue: Boxed? {
get { value }
set { self.value = newValue }
}
}
extension NotCodable: Decodable where Boxed: Decodable {
public init(from decoder: Decoder) throws {
self.value = nil
}
}
extension NotCodable: Encodable where Boxed: Encodable {
public func encode(to encoder: Encoder) throws {
/// Do not encode
}
}
extension NotCodable: Equatable where Boxed: Equatable {
public static func == (lhs: NotCodable<Boxed>, rhs: NotCodable<Boxed>) -> Bool {
lhs.wrappedValue == rhs.wrappedValue
}
}
extension NotCodable: Hashable where Boxed: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(wrappedValue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment