StoredPropertyIterable

Related idea—wouldn't need to be tied to this pitch, but just thought I'd throw it out for future consideration.

It'd be cool to have a compiler-synthesized failable initializer that takes a dictionary of partial keypaths to property values:

struct Person: StoredPropertyInitializable {
    var firstName: String
    var age: Int

    // compiler-synthesized:
    init?(propertyValues: [PartialKeyPath<Person>: Any]) {
        guard
            let firstName = propertyValues[\.firstName] as? String,
            let age = propertyValues[\.age] as? Int
        else {
            return nil
        }

        self.firstName = firstName
        self.age = age
    }
}

Such a feature would enable, for example, the creation of generic builder types.

3 Likes