Skip to content

Instantly share code, notes, and snippets.

@raxityo
Last active August 7, 2020 03:05
Show Gist options
  • Save raxityo/63cf046d8a7cd8e782a2d545fc63a330 to your computer and use it in GitHub Desktop.
Save raxityo/63cf046d8a7cd8e782a2d545fc63a330 to your computer and use it in GitHub Desktop.
Decode the `Codable` value or set it to `nil
/// 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