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




Software Engineer Shuffling between iOS and Gaming

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to build An E-commerce website using both Php and IoT software Development and its uses

HTTP Request Methods: A Complete Guide

Building Resilience Around Uncharted Technologies

Setting up OpenCV for JAVA.

Dev practices you should adopt during Lockdown.

Development update: Increased work difficulty upgrade status 2

Docker IPV6 Guide

Enterprise Application Security

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
Keerthiraj Su

Keerthiraj Su

Software Engineer Shuffling between iOS and Gaming

More from Medium

Swift compiler

[Swift] Struct vs Class

Swift| Closures

Everyone can code Puzzles — Hypocycloid