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.

@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

--

--

--

Software Engineer Shuffling between iOS and Gaming

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

Recommended from Medium

Swift Creating Custom Neumorphic View using UIKit

Swift Enums, Mind the Gap: EnumKit to the Rescue

SwiftUI-How to build Design System

Update on #Hyprr with an overview of a new Video Preview feature and the updated AI.

Remote File Manager for iOS

Android vs iOS (Coming soon!)

Five Secrets That iOS App Developers Won’t Tell Us

Crowdin CDN— streamline the localization process (iOS)

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

Everyone can code Puzzles — Hypocycloid

Swift| Property Observers

Type-safe assets in Swift

Swift compiler