Where do I read about which declarations the `@available` attribute can be applied to?

I skimmed through the section on the available attribute on The Swift Programming Language: Redirect but didn't find a mention of exactly which declarations they can be applied to. I was looking for stored properties in particular but couldn't find a mention of properties at all.

Where should I look for this info?

Background

I can apply available to a static var in a class, and it compiles. Then I read this, allegedly from the Xcode 14 release notes:

Stored properties in Swift can’t have type information that is potentially unavailable at runtime. However, prior to Swift 5.7 the compiler incorrectly accepted @available attributes on stored properties when the property had either the lazy modifier or an attached property wrapper. This could lead to crashes for apps running on older operating systems. The Swift compiler now consistently rejects @available on all stored properties.

I'm not using lazy modifiers or property wrappers (Xcode 13.3) so shouldn't my use be rejected? Or is it technically incorrect to call static class variables "properties" (the docs say "You define type properties with the static keyword", so I assume not) or "stored" (the docs say "Stored type properties can be variables or constants", so I assume not)?

If this is not addressed in TSPL we should fix that. That said, I would generally trust the compiler to diagnose illegal uses of an attribute. I hope it is generally rare to have bugs like the one that lead to the fix that the release note refers to.

To help you reason about the case you're wondering about, the reason @available is rejected on stored properties that are members of a class or a struct is that stored properties affect the memory layout of an instance of a type and the compiler and runtime haven't been taught how to handle layout dynamically with respect to potentially unavailable types. This is a limitation that we're hoping to eventually lift rather than a fundamental design constraint. On the other hand, the underlying storage for static properties is laid out at compile time so the same limitation doesn't apply and @available is legal on them today.

Thank you for the explanation and links! That confirms what I suspected with regards to memory layout. Also nice to know that it's a possibility for the future.

I was a bit worried that a future 5.7 would stop compiling this even though I couldn't see an immediate problem for non-instance stored properties.

1 Like