SwiftLint icon indicating copy to clipboard operation
SwiftLint copied to clipboard

Rule Request: [no_number_literal_calculation]

Open KS1019 opened this issue 3 years ago • 1 comments

New Issue Checklist

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.


  1. Why should this rule be added?

This can help users detect type inference-heavy codes and rewrite them easily.

  1. 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
  1. Should the rule be configurable, if so what parameters should be configurable? No
  2. 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 * 24 as their choice of coding style so this rule should be opt-in.

KS1019 avatar Nov 20 '22 01:11 KS1019

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

jpsim avatar Nov 25 '22 16:11 jpsim