Swift – Function Body Length Violation or Line Length Violation

Viewed 6245

I have a function on Xcode (swift) that returns a very long array, that is one word per line. Like

static func en() -> [String] {
    [
        "a",
        "about",
        "above",
        "after",
        "again",
        "against",
        "all",
        "am",
        ...

When I try to compile this I get:

Function Body Length Violation: Function body should span 40 lines or less excluding comments and whitespace: currently spans 175 lines (function_body_length)

if I try to remove the line feeds and add spaces instead I get this

Line Length Violation: Line should be 120 characters or less: currently 1492 characters (line_length)

I think the problem is SwiftLint.

How do I solve this? How do I disable this error.

2 Answers

Option 1: adapt your layout or your design

Your problem seems to be caused by a long array of English words in the source code.

A simple way between one item per line and one line with all the items, would be to spread this data on several lines:

1492 chars broken down into lines of 120 gives 13 lines. If you take into consideration the average English word length of 4.7 (in your case an average unsecable token length of 6.7 with the enclosing quotes, you might to have to shift some of the wors on extra lines. DOing the math, in average, the extra lines have to contain 88 chars extra (6.7*13) so a 14th line. You have still plenty of margins in view of the 175 line limits ;-)

An even better approach, would be to store data in a file and load the data into an array dynamically at run-time. Not only won't you overweight your source code, but in addition, you'd facilitate maintenance of the list with new words, as well as internationalization.

Option 2: configure your linter

The relativeley small line length and body length limits are not about syntax or compiler limitations. It's static analysis rules intended to challenge you write more readable code.

You can disable the rules:

  • at project level, in the file .swiftlint.yml
  • in the source code, with a comment // swiftlint:disable <rule1> [<rule2> <rule3>...]

You can find practical examples with the line_length in this SO question

I guess you can put your array in a json file and decode it like that.

if let url = Bundle.main.url(forResource: "Filename", withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let array = try! JSONDecoder().decode(YourModel.self, from: data)
            // deal with it.
        } catch {
            print("error",error)
        }
    }
Related