Dynamic lookup In Swift

Keerthiraj Su
1 min readDec 20, 2021

Apple introduce User-defined “Dynamic Member Lookup” Types. The new @dynamicMemberLookup attribute provides dot syntax which are resolved at runtime

That feature helps swift to develop as scripting language. One of the powerful feature of swift is subscripts. Subscripts to access elements within various collections, like arrays and dictionaries.

Adding subscripts to any class or structure helps to access its property, regardless of whether that property actually exists or not.

@dynamicMemberLookup
struct Vehicle {
subscript(dynamicMember car: String) -> String {
let properties = ["brand": "Tesla", "year": "2011"]
return properties[car, default: ""]
}
}

Since the above type supports dynamic member lookup, we can use any random name when accessing one of its properties, This will compile clean and doesn’t throw any error.

let newVehicle = Vehicle()
print(newVehicle.brand)
print(newVehicle.year)
print(newVehicle.colour)

Here brand, year and colour doesn’t throw any error, However they are looked up at runtime.

This will print “tesla” and “2011” and an empty string since our dictionary doesn’t have “colour “key.

This feature is very useful for interoperability between swift and other languages like python, javascript and ruby. Basically for bridging between different scripting languages.

@dynamicMemberLookup can be used in classes, struct, enums and protocol it also supports inheritance.

Github link: https://github.com/apple/swift-evolution/blob/master/proposals/0195-dynamic-member-lookup.md

--

--