Last active
August 7, 2020 03:05
-
-
Save raxityo/63cf046d8a7cd8e782a2d545fc63a330 to your computer and use it in GitHub Desktop.
Decode the `Codable` value or set it to `nil
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
/// Attempt to decode value or return `nil` | |
/// | |
/// Example: | |
/// ``` | |
/// struct User { | |
/// @DecodeOrNil var avatarURL: URL? // Sets it to nil if server sends an invalid URL for avatarURL. | |
/// } | |
/// ``` | |
@propertyWrapper | |
public struct DecodeOrNil<T: Codable>: Codable { | |
public var wrappedValue: T? | |
public init(wrappedValue: T?) { | |
self.wrappedValue = wrappedValue | |
} | |
public init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
wrappedValue = try? container.decode(T.self) | |
} | |
public func encode(to encoder: Encoder) throws { | |
try wrappedValue.encode(to: encoder) | |
} | |
} | |
extension DecodeOrNil: Equatable where T: Equatable {} | |
extension DecodeOrNil: Hashable where T: Hashable {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment