Store values using unique, randomly generated identifiers

Storage

Store values using unique, randomly generated identifiers.

This packages consists of three types: A Storage class, a UniqueIdentifiable protocol,
and a UniqueID struct.

You use Storage‘s auto-getting and setting methods to manipulate the values of computed
properties without the need for extra, often unnecessary code.

Create a type, and declare conformance to the UniqueIdentifiable protocol. The only
requirement is that you implement an id property of the UniqueID type.

struct Apple: UniqueIdentifiable {
    let id = UniqueID()
}

On its own, this has very few practical applications, but when combined with the Storage
type, the list of applications grows. Storage‘s usefulness becomes apparent when dealing
with protocol extensions. You can use the id property to get and set computed properties,
something that otherwise would be very difficult to achieve, as extensions in Swift cannot
contain stored properties.

fileprivate var storage = Storage()

protocol Fruit: UniqueIdentifiable { }

extension Fruit {
    var name: String {
        get { storage.autoGet(id, backup: "apple") }
        set { storage.autoSet(newValue, id) }
    }
    
    var color: String {
        get { storage.autoGet(id, backup: "red") }
        set { storage.autoSet(newValue, id) }
    }
    
    var shape: String {
        get { storage.autoGet(id, backup: "round-ish") }
        set { storage.autoSet(newValue, id) }
    }
}

The properties above automatically get stored under new ids that are created by combining
the id of the instance of Fruit with an id that is synthesized from the name of the
property. In the example above, name‘s value is tied to the name “name”, color‘s value
is tied to the name “color”, and shape‘s value is tied to the name “shape”. Each one can
only be set or retrieved using the id of the instance that stored it, ensuring that these
properties remain part of their instances.

You can also provide a backup value in the event that the property has not been set. This
lets you avoid having to mark the properties as optional, and provide a default state for
every instance of a type. The Fruit type above, for example, will initialize to a red,
round-ish apple.

GitHub

View Github