Skip to content

Instantly share code, notes, and snippets.

@wildthink
Created June 5, 2018 21:35
Show Gist options
  • Save wildthink/2ad017b91ca92d29322be4c69ffe4411 to your computer and use it in GitHub Desktop.
Save wildthink/2ad017b91ca92d29322be4c69ffe4411 to your computer and use it in GitHub Desktop.

[Pitch] Introduce “Dynamic Member” fulfillment of Protocols

Hi All,

To complement the @dynamicMemberLookup feature I think types with dynamic member lookup should automatically be considered to conform to protocol properties that can be satisfied with a dynamicMember subscript.

protocol PersonProtocol {
    var name: String
    var birthdate: Date
}

@dynamicMemberLookup
struct Person: PersonProtocol {

    subscript(dynamicMember member: String) -> String {
        let properties = ["name": "Jon Appleseed", "city": "Cupertino"]
        return properties[member, default: "<no \(member)>"]
    }
    
    subscript(dynamicMember member: String) -> Date {
        let properties = ["birthdate": Date()]
        return properties[member, default: Date()]
    }
}

@dynamicMemberLookup
extension Person: PersonProtocol {}

This would be an additive opt-in feature and not cause any incompatibilities. It would allow dynamic objects to more easily satisfy protocols in a type safe manner and enable Xcode autocomplete and potentially useful compiler hints.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment