Skip to content

Instantly share code, notes, and snippets.

@aainaj
Created June 20, 2020 06:49
Show Gist options
  • Save aainaj/c12132601c0f04fb832aeff6f6307a48 to your computer and use it in GitHub Desktop.
Save aainaj/c12132601c0f04fb832aeff6f6307a48 to your computer and use it in GitHub Desktop.
DefaultEmptyArray Property Wrapper
import Foundation
@propertyWrapper
public struct DefaultEmptyArray<Element: Codable>: Codable {
public var wrappedValue: [Element]
public init(wrappedValue: [Element]) {
self.wrappedValue = wrappedValue
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self.wrappedValue = (try? container.decode([Element].self)) ?? []
}
public func encode(to encoder: Encoder) throws {
try wrappedValue.encode(to: encoder)
}
}
struct Employee: Codable {
@DefaultEmptyArray var types: [EmployeeType]
}
enum EmployeeType: String, Codable {
case HouseKeeping
case Manager
case Cashier
}
let employeeJSON = #"{ "types": ["Manager", "Cashier", "House-Keeping"] }"#.data(using: .utf8)!
let decodedResponse = try JSONDecoder().decode(Employee.self, from: employeeJSON)
print(decodedResponse)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment