Rule Request: [no_number_literal_calculation]
New Issue Checklist
- [x] Updated SwiftLint to the latest version
- [x] I searched for existing GitHub issues
New rule request
I run into code like the below a few times
let secondsInOneDay = 60 * 60 * 24
Since this kind of code can slow the type inference, the calculation should be done beforehand and only the answer should be used.
let secondsInOneDay = 86400
This rule should calculate the expression and replace it when running swiftlint fix.
Note Since (I believe) this rule would be a subset of no_magic_numbers, it might be better if this was a configuration of no_magic_numbers rather than a separate rule.
- Why should this rule be added?
This can help users detect type inference-heavy codes and rewrite them easily.
- Provide several examples of what would and wouldn't trigger violations.
Triggering:
let secondsInOneDay = 60 * 60 * 24
let n = 4
let secondsInNDays = 60 * 60 * 24 * n
Non triggering:
let secondsInOneDay = 86400
let n = 4
let secondsInNDays = 86400 * n
- Should the rule be configurable, if so what parameters should be configurable? No
- Should the rule be opt-in or enabled by default? Why?
Personally I would love to have this rule by default but I think some people prefer
60 * 60 * 24as their choice of coding style so this rule should be opt-in.
This is a fine rule if you want it, but should be opt-in. In many cases, splitting up a calculation will clarify the intention over having the result hardcoded, and the compiler can usually optimize this so the result is computed at compile time and inlined in the binary.
For example, the assembly for both these functions is the same:
func foo() -> Int { 2 * 2 }
and
func foo() -> Int { 4 }
produces identical assembly:
output.foo() -> Swift.Int:
push rbp
mov rbp, rsp
mov eax, 4
pop rbp
ret