4

How do I get the property name as a string?

class Person {
    var firstName: String
    var lastName: String
    var downloading: Bool

    func excludePropertiesFromCloud() -> [String] {
        return //here I want to return ["downloading"]
    }
}

I would like to avoid having to type return ["downloading"] to prevent errors if the name of the variable changes later on.

To get the class name you can use String(describing: Person.self), so I am looking at something similar for properties.

Note:
Although the title of the question is very similar to Get a Swift Variable's Actual Name as String, it is clear that the accepted answer in the original question returns the value of the property and does not answer this straightforward question. The original question is the first to come up on any google search with "Swift get property name", and the answer answers something else, as pointed to by @MarqueIV. This is why I created this question

Duzmac
  • 421
  • 1
  • 5
  • 14
  • https://stackoverflow.com/a/33516339/1979882 – Vyacheslav Jan 28 '18 at 21:10
  • 1
    Sorry but although the title of the question is very similar, it is clear that the accepted answer in the original question does not answer this straightforward question. The original question is the first to come up on any google search with "Swift property name", and the answer answers something else, as pointed to by @MarqueIV. This is why I created this question. – Duzmac Jan 29 '18 at 05:56

1 Answers1

5

If you are ok with making your properties @objc you can get the property name like so:

class Person {
    @objc var firstName: String
    var lastName: String
    var downloading: Bool

    func excludePropertiesFromCloud() -> [String] {
        return [#keyPath(firstName)]
    }
}
gasho
  • 1,926
  • 1
  • 16
  • 20
  • 2
    How does this solve the problem asked in the question? If you rename the property, you need to update the keyPath. – rmaddy Jan 28 '18 at 21:18
  • 4
    We are accessing the property directly by name. If for some reason we change the property name, we will get a compile time error. – gasho Jan 28 '18 at 21:29
  • I am using Core Data and the menu *Editor / Create NSManagedObject Subclass...*. Every time the code is regenerated the @objc is overwritten unfortunately – Duzmac Jan 29 '18 at 19:21