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!
source
share