Swift Dynamic Member Lookup Example

1. Introduction

Swift's Dynamic Member Lookup introduced by Swift Evolution proposal SE-0195 allows types to define their behavior when accessed using dot syntax for members not statically known to exist. It's a feature that enhances Swift's interoperability with dynamic languages like Python and JavaScript, without sacrificing type safety. Here's how this feature is implemented and used.

2. Source Code Example

// Define a structure with dynamic member lookup capability
struct DynamicStruct {
    private var properties: [String: String] = [:]
    // This custom subscript enables the dynamic member lookup
    subscript(dynamicMember member: String) -> String? {
        get {
            // Return the value for the dynamic member
            return properties[member]
        set {
            // Set the value for the dynamic member
            properties[member] = newValue

// Create an instance of our dynamic structure
var dynamicObj = DynamicStruct()
dynamicObj.username = "swift_user"   // Set a dynamic property
dynamicObj.email = "swift@example.com"   // Set another dynamic property

// Access the dynamically set properties
print(dynamicObj.username)  // Outputs: Optional("swift_user")
print(dynamicObj.email)     // Outputs: Optional("swift@example.com")



3. Step By Step Explanation

1. Defining Dynamic Member Lookup:

- The @dynamicMemberLookup attribute is applied to our DynamicStruct. This tells Swift that the struct will use dynamic member lookup.

- Inside this struct, we keep a private dictionary properties that stores the dynamic members.

- The custom subscript dynamicMember allows for the getting and setting of values for dynamic properties with dot syntax. This is the heart of the dynamic member lookup.

2. Utilizing Dynamic Properties:

- We instantiate DynamicStruct.

- Without having predefined properties like username or email in our struct, we're able to set values for them due to our dynamic member lookup implementation.

3. Accessing Dynamic Properties:

- Accessing properties like username and email leverages our custom subscript, fetching the previously set values. 

Dynamic Member Lookup is a flexible feature in Swift, especially useful for dynamic data handling or interfacing with dynamic languages. It should be used wisely to maintain Swift's renowned type of safety and clarity.