Created
June 3, 2022 20:59
-
-
Save mackoj/ac92a8d6a7058136d41aaf41f58e08d1 to your computer and use it in GitHub Desktop.
This PropertyWrapper allow you to force a value when decoding a property
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 | |
/// This allow to force a default value when using codable | |
/// This will force `isEditMode` to always have `false` when decoding it | |
/// @MockCodable(defaultValue: false) public var isEditMode: Bool = true | |
@propertyWrapper | |
public struct MockCodable<Value> { | |
private var value: Value | |
private var defaultValue: Value | |
public init(wrappedValue: Value, defaultValue: Value) { | |
self.value = wrappedValue | |
self.defaultValue = defaultValue | |
} | |
public var wrappedValue: Value { | |
get { value } | |
set { self.value = newValue } | |
} | |
} | |
extension MockCodable: Decodable where Value: Decodable { | |
public init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
let extracted = try container.decode(Value.self) | |
self.value = extracted | |
self.defaultValue = extracted | |
} | |
} | |
extension MockCodable: Encodable where Value: Encodable { | |
public func encode(to encoder: Encoder) throws { | |
var container = encoder.singleValueContainer() | |
try container.encode(self.defaultValue) | |
} | |
} | |
extension MockCodable: Equatable where Value: Equatable { | |
public static func == (lhs: MockCodable<Value>, rhs: MockCodable<Value>) -> Bool { | |
lhs.wrappedValue == rhs.wrappedValue | |
} | |
} | |
extension MockCodable: Hashable where Value: 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