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

Default Implementation #52

@codeOfRobin

Description

@codeOfRobin

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")
        }

    }

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions