Referencing types, possibly in another library, through a typealias question

I've cobbled together a library where I'd really like to use SwiftUI's Angle type. But aside from that type, the library could easily be used on its own.

To solve this earlier, I tried to take the tack in the source code of checking to see if SwiftUI could be imported, and if so - using that Angle, otherwise using my own with a typealias setup:

#if canImport(SwiftUI)
    import SwiftUI
    public typealias Angle = SwiftUI.Angle
#else
    public typealias Angle = SimpleAngle
#endif

That said, when I'm compiling this with Swift 5.9, I'm getting a Swift 6 warning now when I'm using an initializer that could map to the SwiftUI type:

let angle: Angle = Angle.degrees(90)

Static method 'degrees' cannot be used in a default argument value because 'SwiftUI' was not imported by this file; this is an error in Swift 6

And beneath that: The missing import of module 'SwiftUI' will be added implicitly

I'm obviously making some poor assumptions about how the types are resolved, but I'm not 100% certain on HOW to resolve it. I thought having the typealias in the module would propagate to all the rest of the files so that I could try the "Use SwiftUI's Angle if it's available, otherwise use my somewhat crappy substitute" pattern.

Is this a bit of a fool's errand and I'd be better off embracing my own type or requiring SwiftUI in my library? Or is there another pattern that I'd be better off using in this kind of scenario?

You may be able to get it working by using @_exported import SwiftUI, to make the symbols more visible, but that makes all of SwiftUI visible. You could try limiting that to struct SwiftUI.Angle but I don't know if that'll help.

1 Like

Thanks @Jon_Shier - I was really hoping for a "use SwiftUI's Angle if it's available at compilation time, otherwise use this other thing" pattern. I love the type, but don't want to bind the library to only working with SwiftUI.

Nothing I said limits it to only working with SwiftUI?

Apologies, I misunderstood what you were suggesting. When I dropped in the @_exported in front of the import (but still within the conditional compilation section), the warnings dropped off entirely. Solves the warnings issue for me entirely!

Thank you!

1 Like