Dan L
Dan L

Reputation: 88

Access/print/log variable name in Swift

Much of what I have been reading on this subject leads me to believe this isn't possible at the moment, but I'm curious if anyone knows how to print a variable's actual name in Swift.

My use case here is specifically for debugging/logging purposes to help with accurately tracking down the source of an error in a guard statement. My hope is that I won't need to manually pass in a string and can just have a default parameter in the function signature. Also, since guard statements are a common Swift convention, for myself and others potentially doing something like this, this could be a big time saver and a bit more reliable than manually typing each time this is implemented...

More or less what I'm thinking is below—plus I would likely utilize other info like #file, #line in the guarded() function

extension Optional {
    func guarded(variableName: String = #variableName, caller: String = #function) -> Optional {
        if self == nil {
            log.warning(message: "Guard statement failed to unwrap variable: \(variableName) in function: \(function)")
        }
        return self
    }
}

Which would be useful in a situation like this:

func sampleFunction(_ funkyVariable: String?, boringVariable: String?) {
    guard let funkyVariable = funkyVariable.guarded(), let boringVariable = boringVariable.guarded() else { 
        // Custom handling of else condition if necessary
        return 
    }

    print("\(funkyVariable) and \(boringVariable) aren't nil!")
}

Then, when it's called:

sampleFunction(funkyVariable: "string", boringVariable: nil) 
// Results in logger message: "Guard statement failed to unwrap variable: boringVariable in function: sampleFunction"

Would love to see if you have any thoughts beyond manual efforts here. Thanks!

Upvotes: 4

Views: 922

Answers (1)

Alexander
Alexander

Reputation: 63271

You can't. Variable names are an abstraction are strictly for programmers. The compiler just deals with registers and memory addresses. For such a thing to work, it would need to be an explicit language feature, which it (currently) isn't

Upvotes: 1

Related Questions