A Collection of Code Snippets in as Many Programming Languages as Possible
This project is maintained by TheRenegadeCoder
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.
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.
No 'How to Implement the Solution' section available. Please consider contributing.
No 'How to Run the Solution' section available. Please consider contributing.