How can I get name of variable (it is an object) as string at runtime in Swift?

class Employee {

    func calculateSalary() {

         -> how can I print name of the variable call in this function?

    }

}

Example:

let johnny = Employee()

johnny.calculateSalary() 

-> It will print "johnny" in function calculateSalary() 

Replies

AFAIK, you cannot do this directly.

But you could pass the name to the func:

class Employee {

    func calculateSalary(_ name: String) {
        print(name)
         // -> how can I print name of the variable call in this function?
    }

}

let johnny = Employee()

johnny.calculateSalary("johnny")

Or create a property with the name:

class Employee {

    var name: String = ""
    
    init(_ name: String) {
        self.name = name
    }
    
    func calculateSalary() {
        print(name)
         // -> how can I print name of the variable call in this function?

    }

}

let johnny = Employee("johnny")

johnny.calculateSalary()
  • Yes, I see. I need print it for debug only so I think I don't need to do that. Thanks anyway !!!

Add a Comment

Effectively it is less critical for debug.

however, it is a good design to have a way to identify user. You will probably need it later on.

you could use the name (as proposed) or create a unique ID

class Employee {
  let id = UUID()

Good continuation and don’t forget to close the thread.

What you are trying to do can probably best be accomplished with the built in logging system. These can easily log (print out) the message you give it (along with the source file name, func/method, line number in the source code, etc.). Take a look through the built in logging facilities here, they are VERY helpful: