Factorial in Swift

Published on 03 May 2026 (Updated: 03 May 2026)

Welcome to the Factorial in Swift page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

import Foundation

let usage = """
    Usage: please input a non-negative integer
    """

extension FixedWidthInteger {
    var factorial: Self? {
        guard self >= 0 else { return nil }
        guard self > 1 else { return 1 }

        var result: Self = 1

        for i in 2...self {
            let (value, overflow) = result.multipliedReportingOverflow(by: i)
            if overflow { return nil }
            result = value
        }

        return result
    }
}

extension StringProtocol {
    var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) }
}

guard
    let raw = CommandLine.arguments.dropFirst().first?.trimmed,
    let n = Int(raw),
    let result = n.factorial
else {
    print(usage)
    exit(1)
}

print(result)

Factorial in Swift was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.