For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/swift-code-style/specify-return-type.md. A documentation index is available at /llms.txt.
This product is not supported for your selected Datadog site. ().

Metadata

ID: swift-code-style/specify-return-type

Language: Swift

Severity: Error

Category: Code Style

Description

In Swift, specifying a function’s return type is crucial for readability, maintainability, and to avoid potential runtime errors. This rule enforces that the return type of a function should be explicitly stated using the ‘->’ symbol when the function returns a value.

Not specifying a return type for a value-returning function can lead to confusion for other developers who might use your function, as they won’t be able to predict what kind of value they should expect. Additionally, it can cause errors if the function returns a different type than expected. Functions that return nothing (Void) may omit the return type; for example, func viewDidAppear(_ animated: Bool) { refresh() } is compliant.

To adhere to this rule, specify the return type when your function returns a value: e.g. func addTwoNums(num1: Int, num2: Int) -> Int. For functions that return nothing, you may omit -> Void; adding it explicitly (e.g. func doSomething() -> Void { }) is also compliant.

Non-Compliant Code Examples

func addTwoNums(num1: Int, num2: Int) {
    return num1 + num2;
}

Compliant Code Examples

func addTwoNums(num1: Int, num2: Int) -> Int {
    return num1 + num2;
}
public func getValue(for name: String) -> String? {
    return value
}
func doSomethig() {
    something()
}
func checkCanEncode(value: Any?) throws {
    guard canEncodeNewValue else {
        throw EncodingError.invalidValue(value as Any, context)
    }
}
func nestedContainer() -> any SingleContainer {
    return new SingleValueContainer()
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
    let pinnedKeysInServerKeys: Bool = {
        for serverPublicKey in trust.af.publicKeys {
            if keys.contains(serverPublicKey) {
                return true
            }
        }
        return false
    }()
    if !pinnedKeysInServerKeys {
        throw AFError.serverFailed()
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security