Skip to content

Rule Request: Forbid NaN comparison #2086

Closed

Description

@guilhermearaujo

New Issue Checklist

Rule Request

Instances of FloatingPoint (eg Float, Double, CGFloat, etc) should not be compared to a NaN using equal-to or not-equal-to operators. Doing so will result in unwanted or unpredicted behaviour, as comparisons using these operators will always return false and true, respectively.

  1. Why should this rule be added? Share links to existing discussion about what
    the community thinks about this.

Apple docs on FloatingPoint.isNaN:

Because NaN is not equal to any value, including NaN, use this property instead of the equal-to operator (==) or not-equal-to operator (!=) to test whether a value is or is not NaN.

StackOverflow discussion on IEEE Standard 754 (quoting the Standard)

Four mutually exclusive relations are possible: less than, equal, greater than, and unordered. The last case arises when at least one operand is NaN. Every NaN shall compare unordered with everything, including itself.

  1. Provide several examples of what would and wouldn't trigger violations.

Would trigger

if myFloating == .nan { ... }  // Same as `if false`
if myFloating != .nan { ... }  // Same as `if true`
if myFloating >= .nan { ... }  // Same as `if false`
if myFloating < .nan { ... }   // Same as `if false`
// Etc.

Would NOT trigger

if myFloating.isNaN { ... }
if !myFloating.isNaN { ... }
  1. Should the rule be configurable, if so what parameters should be configurable?
    I can't think of any.

  2. Should the rule be opt-in or enabled by default? Why?
    Enabled by default, because comparing, for instance, a Double to Double.nan will always return false. This can cause the program to have an undesired behaviour. The correct way is to check the isNaN property.

Activity

  1. added
    rule-request
    on Mar 7, 2018
  2. added a commit that references this issue on Feb 8, 2020
    8270227
  3. added a commit that references this issue on Feb 9, 2020
    fdd16a6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    rule-request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions