UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Get a property of an object by passing a string or enum instead of using dot notation.

Forums > Swift

This might be something basic that I overlooked or couldn't find, but is there a method in Swift that I can get an object's property by passing it the property name instead of having to use dot notation?

Much like in javascript, you can get an object's property using the .get() method

let name = object.get("name")

instead of Swift's

let name = object.name

I've built my own method to do this but had to hard code the object's properties into the method, I was wondering if there was a built in method that does this for any object "automagically".

func getProperty(for property: PlacemarkLevel) -> LocationAreaType? {
      switch property {
      case .name                        :       return nil
      case .thoroughfare                :       return self.thoroughfare
      case .subLocality                 :       return self.subLocality ?? nil
      case .locality                    :       return self.locality ?? nil
      case .administrativeArea          :       return self.administrativeArea ?? nil
      case .subAdministrativeArea       :       return self.subAdministrativeArea ?? nil
      case .country                     :       return self.country ?? nil
      }
  }

thanks,

2      

Simple answer: no.

If you really want to go this way you could use a data structure like a Dictionary. But this has other disadvantages.

Swift and JavaScript just have different syntax. Additionally, with the String method the IDE can't help you with typos.

3      

thanks @Hatsushira

2      

Jay wants to see what's in the looking glass:

... is there a method in Swift that I can get an object's property by passing it the property name ....

In Java this is called Reflection? This allows an object, at runtime, to look into itself and examine what properties it has.

Of course, if you're looking at your reflection, you might be looking at a mirror. Swift has a Mirror class for this.

Hope this helps you on your trip through the Looking Glass?

See-> Looking in the Mirror

The Google helped find sample code. See -> Mirror Example

What's your solution?

Please return here and tell us how you solved your conundrum.

2      

Fascinating! Thanks, @Obelix!

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.