realm / SwiftLint

A tool to enforce Swift style and conventions.
https://realm.github.io/SwiftLint
MIT License
18.46k stars 2.2k forks source link

Rule Request: Educated Sorting #1038

Open jpsim opened 7 years ago

jpsim commented 7 years ago

There area few arrays in SwiftLint's own source that are alphabetically sorted, like masterRuleList and the Linux allTests extensions.

The same thing could apply to enum members, dictionaries, constants, etc.

For example, SourceKitten's SwiftDeclarationKind enum members are all sorted.

It'd be awesome if SwiftLint could automatically infer which sets of declarations were mostly sorted and trigger a warning.

For example, if an array of 10 items only has 2 out-of-order elements, odds are that these are just mis-ordered. This likelihood goes up as the number of total items increases and the number of out-of-order elements decreases.

This could be configurable by minimum thresholds, and probably be made correctable in simple cases.

JamieEdge commented 7 years ago

Hey, so I've started work on a rule for this (see the related commit above), however when I run unit tests (adding the below code to RulesTests.swift), I'm finding the values that are sent in the dictionary in the method call validateFile(file:kind:dictionary:) to be very different to 'real' ones.

    func testEducatedSorting() {
        verifyRule(EducatedSortingRule.description)
    }

Any idea why the body offset and body length come through as out of range values during unit testing? I may just be misunderstanding the purpose of these variables.

(lldb) po file.contents.characters.count
59

(lldb) po bodyOffset
93

(lldb) po bodyLength
27
jpsim commented 7 years ago

The offsets and lengths returned from SourceKit are all in bytes. For multi-byte characters in Strings (e.g. non-ASCII such as emoji), characters.count != bytes.

SourceKitten has a number of conversion methods to help with this, most of which are in String+SourceKitten.swift. Such as String.byteRangetoNSRange(start:length:).

JamieEdge commented 7 years ago

Thanks @jpsim - that's fixed it now!

richellis commented 3 years ago

Would just like to register a vote for this specifically for enum cases and switch statements over enum cases. I like the approach in the linked PR for arrays of a minimum number of cases threshold and inferring that the cases are mostly sorted.