Swift / Print / Log Variable Name

Much of what I read on this subject makes me think that this is not possible at the moment, but I am curious if anyone knows how to print the variable actual name in Swift.

My use case here is specifically for debugging / logging to help with accurately tracking the source of the error in the guard instruction. I hope that I don’t need to manually pass the string and may just have a default parameter in the function signature. In addition, since security instructions are a common Swift convention, for me and others that could potentially do something similar, this can be a big time saver and a bit more reliable than manually setting up every time it is implemented ...

More or less what I think is below plus, I would use other information, for example #file, #linein a functionguarded()

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
    }
}

What would be useful in such a situation:

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 he called:

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

I would like to see if you have any thoughts besides manual efforts here. Thank!

+4
source share
1 answer

You can not. Variable names are an abstraction strictly for programmers. The compiler simply deals with registers and memory addresses. For such work to work, it must be an explicit language function, which it (currently) is not

+1
source

Source: https://habr.com/ru/post/1665945/


All Articles