#function behavior differs based on initializer implementation

Hi there,

I've noticed that the behavior of #function at the type level varies depending on whether the initializer is explicitly implemented or synthesized.

struct S1 {
    let name = #function  // "init(int:)"
    var int: Int
}

struct S2 {
    let name = #function  // "S2"
    var int: Int
    init(int: Int) {
        self.int = int
    }
}

Also, when #function is used with a mutable ivar, it behaves the same as in the S2 case.

struct S3 {
    var name = #function  // "S3"
    var int: Int
}

Why does this happen? This is not an intended behavior, right?

2 Likes

This is expected and intended, yes. #function captures the name of the function in which it was evaluated at compile time. In the first example, the compiler synthesizes a default initializer. In the second example, there is no synthesis, so the default initialization of a property does not occur within the scope of any function, initializer, accessor, subscript, etc. It just occurs within the type's scope—so that's what you get.

Edit: After thinking it over a bit more, this inconsistency does seem like it could be addressed since any initialization path that resolves #function goes through some initializer, either explicitly written or synthesized, so it should be possible to get the name of the initializer in all cases. Please file a GitHub issue!

3 Likes

Done!

3 Likes