Created
June 20, 2020 06:49
-
-
Save aainaj/c12132601c0f04fb832aeff6f6307a48 to your computer and use it in GitHub Desktop.
DefaultEmptyArray Property Wrapper
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 | |
@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