Skip to content
This repository was archived by the owner on Jan 16, 2025. It is now read-only.

Default Implementation #52

Open
codeOfRobin opened this issue Sep 9, 2016 · 0 comments
Open

Default Implementation #52

codeOfRobin opened this issue Sep 9, 2016 · 0 comments

Comments

@codeOfRobin
Copy link

Hey!
Good job on Pantry!
I've built a new extension that inherits from Storable. Added extensions for default implementations (It uses Reflection to generate property-value pairs that's then typecasted to a dictionary. Now, if you want to add caching behaviour to a Struct, simply add Pantryable in an extension.
Here's a Gist

//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 subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant