Skip to content

Instantly share code, notes, and snippets.

@colgraff
Forked from ryantxr/InitStructFromData.swift
Last active August 19, 2017 22:10
Show Gist options
  • Save colgraff/3ed03b30275065cf575252279078058a to your computer and use it in GitHub Desktop.
Save colgraff/3ed03b30275065cf575252279078058a to your computer and use it in GitHub Desktop.
Initialize a struct from data, dictionary etc
// Credit: https://stackoverflow.com/users/887210/colgraff
struct Header {
let version : UInt
let options : UInt
let records : UInt
}
// adds marshaling
extension Header {
enum Keys: String { case version, options, records }
init?(settings: [Keys:Any]) {
guard let marshalled = Header.marshal(settings: settings) else { return nil }
self = marshalled
}
// Execute marshalling
static func marshal(settings: [Keys:Any]) -> Header? {
guard let version = settings[.version] as? UInt else {
return notFound(settings)
}
// add new versions to this `switch`
switch version {
case 0: return marshal0(settings)
default: return notFound(settings) // no match, by default returns a `nil`
}
}
// No version marshaling
static private var notFound: ([Keys:Any]) -> Header? = { (_) -> Header? in
// perhaps log this
return nil
}
// Version 0 marshaling
static private var marshal0: (([Keys:Any]) -> Header?) = { (settings) -> Header? in
guard let version = settings[.version] as? UInt else { return nil }
guard let options = settings[.options] as? UInt else { return nil }
guard let records = settings[.records] as? UInt else { return nil }
return Header(version: version, options: options, records: records)
}
}
let data: [Header.Keys: UInt] = [.version: 0, .options: 5, .records: 121]
if let foo = Header(settings: data) {
print(foo) // Header(version: 5, options: 5, records: 121)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment