Reputation:
I'd like to use the name of function to resolve some problems, but #function
seems not to work well with @inline(__always)
, here is my codes:
@inline(__always) func log() {
print(#function)
}
func a() { log() } // want 'a()', but got 'log()'
func b() { log() }
func c() { log() }
//...
Can anybody explain? or that's just a stupid idea.
Upvotes: 3
Views: 1074
Reputation: 539965
If your intention is to print the name of the function which calls
log()
, then you should pass it as default argument (which is evaluated
in the context of the caller), as demonstrated
in Building assert()
in Swift, Part 2: __FILE__
and __LINE__
in the Swift blog.
Example:
@inline(__always) func log(_ message: String, callingFunction: String = #function) {
print("\(callingFunction): \(message)")
}
func a() { log("Hello world") }
func b() { log("Foo") }
func c() { log("Bar") }
a() // a(): Hello world
b() // b(): Foo
c() // c(): Bar
This works regardless of whether the log
function is inlined or not.
(Inlining does not change the semantics of a program. In particular,
it does not mean that the source code of func log
is included from
the source code of func a()
and compiled as a single function.)
Upvotes: 4