Dynamic lookup In Swift

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.

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()

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



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store