Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The @discardableResult attribute is a compiler directive applied to function, method, or initializer declarations to suppress the default compiler warning emitted when a caller invokes the function without capturing or utilizing its return value. By default, Swift enforces strict return value utilization through static analysis. If a function returns a value, the compiler expects the caller to assign it to a variable, evaluate it in an expression, or explicitly discard it using the wildcard pattern (_ =). Applying @discardableResult alters this behavior for the decorated declaration, signaling to the compiler that ignoring the return value is an intended operation, thereby silencing the unused-result warning.

Syntax

The attribute is placed immediately preceding the func or init keyword.
@discardableResult
func computeAndCache() -> Int {
    let calculatedValue = 42
    // Internal state mutation or caching logic
    return calculatedValue
}

// Caller behavior
computeAndCache()               // Valid: No compiler warning generated
let result = computeAndCache()  // Valid: Return value remains fully accessible

Technical Characteristics

  • Compile-Time Only: The attribute strictly affects compile-time static analysis. It does not alter the runtime behavior, memory allocation, or the actual return type of the function.
  • Caller Flexibility: It provides the caller with the option to either capture the returned data or safely ignore it without requiring the explicit _ = functionCall() syntax.
  • Redundancy: Applying @discardableResult to a function that returns Void (or ()) is redundant, as the Swift compiler inherently permits Void return values to be implicitly discarded.
  • Protocol Conformance: When applied to a method requirement within a protocol, the attribute dictates the compiler behavior for any type calling the method through the protocol interface. Conforming types can also independently apply the attribute to their specific implementations.
Master Swift with Deep Grasping Methodology!Learn More