Logo for tanaschita.com

How to use the @available attribute in Swift

Learn to make Swift code only available for certain language versions or platforms.

06 Feb 2023 · 2 min read

With Swift, we have the possibility to add attributes to our code to give the compiler more information.

One of those attributes is @available which we can use to make our code only available for certain Swift language versions or platforms.

Let's take a look at how to do that.

Sponsorship logo
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

Attributes in Swift

In general, an attribute in Swift is always specified with the @ symbol followed by the attribute's name and optionally its arguments enclosed in parentheses:

@name
@name(arguments)

The @available attribute

The @available attribute always has two or more arguments, separated by a comma, for example:

@available(*, unavailable, renamed: "updateCategories")
func update() {
}

In the above example, we declare the update method as not available on any platform because it was renamed to updateCategories.

Calling the update method will now fail with a compiler error:

update() has been renamed to updateCategories()

Arguments of @available attribute

Let's look at each argument we saw in the example in more detail.

The first argument is always a platform or language name, for example iOS, iOSApplicationExtension, swift. Alternatively, we can use an asterisk * to indicate that the availability applies to all platforms.

The remaining arguments can appear in any order:

The <version number> consists of one to three positive integers separated by periods, for example:

@available(iOS, introduced: 15.1)
struct Content {
}

Combination of @available attributes

We can combine multiple availability declarations as follows:

@available(swift, introduced: 4.0.2)
@available(iOS, introduced: 15.1.1)
struct Content {
}

Shorthand syntax

In case that only an introduced argument is used like we saw in the example above, we have the possibility to use a shorthand syntax as follows:

@available(swift 4.0.2)
@available(iOS 15.1.1, *)
struct Content {
}
Sponsorship logo
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

beyond ios

swift

ios

Introduction to Kotlin for Swift developers - classes, structs & enums

Learn how classes, structs and enums work in Kotlin from a Swift developer's point of view.

25 Sep 2023 · 8 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum