user6683350
user6683350

Reputation:

how can i use `#function` symbol in a `inline` function?

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

Answers (1)

Martin R
Martin R

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

Related Questions