Skip to content

Instantly share code, notes, and snippets.

@codeOfRobin
Created September 9, 2016 13:19
Show Gist options
  • Save codeOfRobin/5de993100210abb22715a959a570585b to your computer and use it in GitHub Desktop.
Save codeOfRobin/5de993100210abb22715a959a570585b to your computer and use it in GitHub Desktop.
//Extensions for Pantry using reflection. Default implementation
public protocol Pantryable: Storable {
func allProperties() throws -> [String: Any]
func toDictionary() -> [String : AnyObject]
}
extension Pantryable {
public func allProperties() throws -> [String: Any] {
var result: [String: Any] = [:]
let mirror = Mirror(reflecting: self)
guard let style = mirror.displayStyle where style == .Struct || style == .Class else {
//throw some error
throw NSError(domain: "com.kayako.kayako", code: 666, userInfo: nil)
}
for (labelMaybe, valueMaybe) in mirror.children {
guard let label = labelMaybe else {
continue
}
result[label] = valueMaybe
}
return result
}
public func toDictionary() -> [String : AnyObject] {
do {
let properties = try self.allProperties()
var result:[String: AnyObject] = [:]
for (key,value) in properties {
if let v = value as? AnyObject {
result[key] = v
}
}
return result
} catch {
fatalError("properties can't be retrieved")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment