Functions Should Not Return Constants

ID

swift.functions_return_constants

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Swift

Tags

code_smell, maintainability

Description

Reports a function whose body is a single return of a literal value. Such functions are almost always better expressed as a named constant or a computed property: the call site reads the same way and the reader does not have to descend into a function body to discover that nothing varies.

func defaultPageSize() -> Int {     // FLAW
    return 50
}

Rationale

A function call signals "this might compute something" — readers follow the call to find out what. When the body is a literal, the contract is just "give me this value", which a constant or computed property states more directly. It also avoids the small but real function-call overhead and makes the value usable in @inlinable / constant-expression contexts.

Remediation

Promote the value to a constant or a computed property, depending on where it lives:

// 1) module-level constant
let defaultPageSize = 50

// 2) static type member
extension Pagination {
    static let defaultPageSize = 50
}

// 3) computed property
struct Pagination {
    var defaultPageSize: Int { 50 }
}

When not to fire

The check is intentionally conservative and skips:

  • functions tagged override or open — those exist to be polymorphic and a subclass / conformance may legitimately reassign the return value;

  • functions inside a protocol declaration or extension — those frequently provide protocol-conformance defaults that look constant but are part of an interface contract;

  • multi-statement bodies, computations, and any function whose return expression reads from a parameter, property, or call result.