Swift Attributes (@available, @discardableResult) Example

1. Introduction

Swift attributes provide additional information about declarations. Two such useful attributes are @available and @discardableResult. The @available attribute indicates the lifecycle of a particular declaration and the platforms and OS versions on which it's available. The @discardableResult attribute, on the other hand, indicates that the return value of a function can be ignored without the compiler generating a warning.

2. Source Code Example

// Using @available to indicate availability of a function
@available(iOS 12.0, macOS 10.14, *)
func availableFunction() {
    print("This function is available on iOS 12.0+, macOS 10.14+")
}

// Function with a result that can be discarded without warnings
@discardableResult
func functionWithDiscardableResult() -> Int {
    return 42
}

// Calling the function but ignoring the result
functionWithDiscardableResult()

// Uncommenting the next line would cause an error if the platform does not meet the requirements
// availableFunction()

Output:

// Output would be empty in this case, as we've commented out the availableFunction() call and the result of functionWithDiscardableResult() is discarded.

3. Step By Step Explanation

1. @available(iOS 12.0, macOS 10.14, ): This attribute marks the availableFunction() as being available on iOS starting from version 12.0 and macOS starting from version 10.14. If you attempt to use this function on an older OS version, the compiler will generate an error. The asterisk () indicates that the function is available on all other platforms without version restrictions.

2. @discardableResult: This attribute is added before the function declaration of functionWithDiscardableResult(). It informs the Swift compiler that callers of this function might choose to ignore the return value, and they shouldn't be warned about it. Without this attribute, if the return value of a function is ignored, Swift would produce a warning.

Using Swift attributes like @available and @discardableResult helps in writing safer and more context-aware code, by giving the compiler, and other developers, hints about the intention and constraints around certain pieces of code.


Comments