Nesting parent struct

Hello there,

I recently found a few inspiration using "name spacing" to have UserDefault keys.
Today I am wondering if it is possible, and if it is, how to do the following :

protocol P { 
}

extension P {
  static func showMyName() {
    print("\(Self.self)")
  }
}

struct A {
  struct B: P {
  }
}

So far, A.B.showMyName() will print "B", but I would love to be able to print "A.B", is there a way to get the "nesting parent" with structs ?

Thanks for your help.

This might be part of what you're looking for:

protocol P {
}

extension P {
    static func showMyName() {
        dump(self) // <-- I've only changed this.
        // Note that in this static func, Self.self == self
    }
}

struct A {
    struct B: P {
    }
}

A.B.showMyName() // Will print eg - YourAppsModule.A.B #0

Thanks a lot guys! Both options work. String(reflecting: self) seems the most appropriate since I want to parse it.

Ah, you definitely can't parse it. The format of String(reflecting:) or even String(describing:) on a type is not guaranteed to be consistent from release to release.

What are you really trying to do?

1 Like

I would love to use a bunch of struct / enum nested in a way that they represent my localization keys.
I took a look at "Laurine" for localization but I feel like it is overkilling to have a bunch of static variables and not taking full advantage of swift.

Here is the full idea :
To automate the create of the keys, with a script like Laurine : for each 'strings' file i would generate an extension of a "Localization" struct that would have nested enums that are String representable. Having auto-completion on localization is really great.
Now, with enums I would also be able to create a test that goes over all of it and make sure that for each language, each key has a non-empty value.

(Additionally, for a current project i am working on, I could also make sure all audio files that are named after the localisation keys are available, for each language).

Do you want something like a Java style inner class?

struct Outer: CustomStringConvertible {
    struct Inner: CustomStringConvertible {
        let outer: Outer
        init(_ outer: Outer) {
            self.outer = outer
        }
        var description: String {
            return "\(outer).Inner"
        }
    }
    var newInner: Inner {
        return Inner(self)
    }
    var description: String {
        return "Outer"
    }
}

let o = Outer()
let i = o.newInner
print(i) // Outer.Inner

I assume, based on his code, what he really wants to do is to perform some sort of conditional operation on a struct, based on its type. Am I correct? There are far better ways to do this, if so.

Please don't revive old topics unless you have a similar question yourself.