Bypassing Swift access control

Is there any way to cheat Swift's access protection? I don't mind going deep and dirty in this case (Mirroring? Codable?, etc?).

The particular protection I want to bypass is this:

struct MyView: View {
    @Environment(\.font) var font // ok
    @Environment(\.foregroundColor) var foregroundColor // Error
    // Error: 'foregroundColor' is inaccessible due to 'internal' protection level

You might be able to with Echo, though I’m not sure how. Built-in reflection doesn’t give you access to computed properties, but Echo might be able to (you’ll have to see if that’s supported). What Codable does is that is uses compile-time synthesis (you could call it static reflection) to gather a type’s field in the types en/decoding. Thus, you would run into the same problem as Swift’s built-in reflection.

Now, if looking up the computed properties on an environment variable doesn’t work, you could try instantiating the type of the environment keys. I think the environment keys are inlined for some environment properties, so going into the interface file should allow you to see the type names. Then, you’d have to the qualified names, e.g. SwiftUI., which I think there are tools for doing. After you have the mangled name, you can call a runtime function to instantiate the type based on the mangled string.

Sorry my response was quite vague: I’m very busy, but I just wanted to give you some pointers for how to approach this problem. Nevertheless, you should now that such mechanisms of accessing private API are not suggested and will probably not be allowed in production apps.

1 Like