Check For Availability Of Stdlib Type

Is there a way to check for the availability of a stdlib type (not a module)?

I’d like to add a #if canImport()-like conditional to some code where Float16 is available. I’d normally just use some #available checks and be fine, but it seems like there’s intermittent support for Float16 depending on hardware for macOS.

I’ve tried using #if swift(>=5.3)since that’s the Swift version Float16 was introduced in, but again because of the hardware limitations for macOS it isn’t restrictive enough.

I’d also like to maintain this library for all supported Swift platforms. I worry a series of @available attributes will grow long and unmaintainable if I try and determine availability for every platform Swift supports.

Is there a compiler or runtime directive I’m missing for checking the availability of Float16?

You can use the same check as the Stdlib is currently checking for Float16.

Check for os and arch. Also this is available on SwiftStdlib 5.3+ which is macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0.

#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
@available(SwiftStdlib 5.3, *)
@inline(never)
public func getFloat16(_ x: Float16) -> Float16 { return _opaqueIdentity(x) }
#endif
1 Like

Without trying it out, on macOS float16 is only available on apple silicon, so you could check for #if arch(arm64)

1 Like

Thanks for the help! Checking the stdlib version seems like the right way to go, but it looks like maybe the SwiftStdlib target for @available is only available for the stdlib compliation? I get a warning that it’s not recognized as a valid platform.

It is just a availability macro for Apple's OS check. eg. macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0.

And you can define similar thing via .enableExperimentalFeature("AvailabilityMacro=xx)

1 Like

Like @Kyle-Ye said, the correct check is:

#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))

@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
extension Float16 { // or whatever
  // Can freely use Float16 here
}

#endif
4 Likes