swiftin

Should the opening brace of a function or control flow statement be on a new line or not ?:) This and many other questions cross my mind when I think about coding style. I love the comment from Ray Wenderlich’s Swift style guide:

"You like braces on new lines @elephantronic ? This will strain our friendship!" …hehe, so it really does matter!:)

But coming back to the main subject: This year one of the items on my to do list is a task to learn more about static code analysis tools: linters, Sonar and everything else that can fight against bad smells. In our previous post Maciej mentioned more about code quality and about Codebeat. Today I would like to concentrate on SwitLint, which can help us keep cohesion in our code without straining friendships in our project team:)

SwiftLint checks the source code for programmatic as well as stylistic errors. This is most helpful in identifying some common and uncommon mistakes that are made during coding. SwiftLint is based on guidelines from Swift style guide. Simply saying it can just helps us with:

  • maintaining a higher level of code discipline,

  • increasing the reliability of the code.

Installation

  • using brew:
 
1
2
3
4
 
$ brew install swiftlint
 
 
  • or by downloading and installing a fresh release.

Necessary after installation check version using command swiftlint versionand compare it to the latest version available on website.

Running

We have two options:

  • just type the following command in the Terminal:
 
1
2
3
4
 
$ swiftlint lint
 
 
  • or we can integrate SwiftLint with Xcode:

RunScript

Just for the test I have run SwiftLint with default options in my current project and I wish I had been using it from the beginning of the project  :

SwiftLint Rules

All available rules which you can use are here.

If you want to have a possibility to control which rule is disabled/enabled and to set thresholds for warnings and errors for a given rule, just create a .swiftlint.yml file in your project directory:

swiftlintYML

You can download the example configuration file from here.

Now by typing in the Terminal swiftlint rules you can check your settings:

SwiftLintRules

Running Options

Sometimes running options can be very useful. Let’s focus on them:

  • -- path The path to the file or directory. For example if you want to lint only one file:
 
1
2
3
4
 
$ swiftlint autocorrect --path just_this_file.swift
 
 
  • -- config The path to SwiftLint’s configuration file .swiftlint.yml:
 
1
2
3
4
 
$ swiftlint lint --config .swiftlint.yml
 
 
  • -- use-script-input-files read SCRIPT_INPUT_FILE* environment variables as files. When using this parameter can be useful? For example when we only would like to lint modified files and new files tracked in our github repository. Example of usage which I found here:
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
if which swiftlint >/dev/null; then
    count=0
    for file_path in $(git ls-files -om --exclude-from=.gitignore | grep ".swift$"); do
        export SCRIPT_INPUT_FILE_$count=$file_path
        count=$((count + 1))
    done
    for file_path in $(git diff --cached --name-only | grep ".swift$"); do
        export SCRIPT_INPUT_FILE_$count=$file_path
        count=$((count + 1))
    done
    
    export SCRIPT_INPUT_FILE_COUNT=$count
 
    swiftlint lint --use-script-input-files
else
  echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi
 
 
 
1
2
3
4
5
6
7
8
 
- git ls-files: outputs the filenames in working directory
- o: (others: Show other (i.e. untracked) files in the output)
- m: (modified) Show modified files in the output
- exclude-from=.gitignore: it omits ignored files
- grep ".swift$" : search only .swift files
 
 
  • -- quiet flag that prevents status messages like ‘Linting ‘ & ‘Done linting’ from being logged.

  • -- reporter generates report with selected format: JSON, Checkstyle, CSV, Xcode. For example:

 
1
2
3
4
 
$ swiftlint lint --reporter json
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
 
{
    "reason" : "Opening braces should be preceded by a single space and on the same line as the declaration.",
    "character" : 23,
    "file" : "../ViewController.swift",
    "rule_id" : "opening_brace",
    "line" : 50,
    "severity" : "Warning",
    "type" : "Opening Brace Spacing"
  },
  ...
 
 

Autocorrect

Very nice feature of SwiftLint is the auto-correction swiftlint autocorrect, which can automatically fix violations in your code. What type of violations can we fix?

  • Closing brace. Closing brace with closing parenthesis should not have any whitespaces in the middle:

closingBrace

  • Colon. Colons should be next to the identifier when specifying a type:

colonRule

  • Comma Spacing. There should be no space before and one after any comma:

commaRule

  • Legacy Constant. Struct-scoped constants are preferred over legacy global constants:


Very nice article explaining the why.

  • Legacy Constructor. Swift constructors are preferred over legacy convenience functions:



  • Opening Brace Spacing. Opening braces should be preceded by a single space and on the same line as the declaration:



  • Statement Position. Else and catch should be on the same line, one space after the previous declaration:



  • Trailing Newline. Files should have a single trailing newline:



  • Trailing Semicolon. Lines should not have trailing semicolons:



  • Trailing Whitespace. Lines should not have trailing whitespace:



Cyclomatic Complexity

In SwiftLint you can find very nice rules, for example:

  • File length rule: Files should not span too many lines.
  • Function Parameter Count: Number of function parameters should be low.
  • Type Body Length: Type bodies should not span too many lines.
  • Type Name Rule: Type name should only contain alphanumeric characters, start with an uppercase character and span between 3 and 40 characters in length.

But when I first looked at the rules list my attention was captured by the Cyclomatic Complexity rule. What is this? Wiki says:

"is a software metric (measurement), used to indicate the complexity of a program. It is a quantitative measure of the number of linearly independent paths through a program’s source code."

This parameter just says how complex our functions are. To many ifs are not recommended. If you add 3rd nested if, you should wait a moment and reconsider your solution. This is my weakness, because sometimes I propose really overcomplicated solutions for quite easy problems: it can always be done much simpler… great rule for using by me:) How to add this bodyguard to your config file? Just add it on the end on .swiftlint.yml:

 
1
2
3
4
5
6
 
cyclomatic_complexity:
  warning: 2 # two nested ifs are acceptable
  error: 5   # six nested ifs shows warning, 6 causes compile error
 
 

最新文章

  1. Hbase数据导入导出
  2. Android EditText输入格式设置
  3. Flask的socket.error:10053
  4. 【原】iOS学习38网络之数据解析
  5. maven总结3
  6. Setting up Nutch 2.1 with MySQL to handle UTF-8
  7. 使用const 提高函数的健壮性
  8. android中获取屏幕的信息
  9. C#语言和SQL Server 数据库处理
  10. VNF网络性能提升解决方案及实践
  11. usaco-5.3.3Network of Schools 校园网
  12. 【Selenium】各种方式在选择的时候应该怎么选择
  13. IPV4/IPV6双协议栈配置案例
  14. goaccess
  15. 八、IIC 接口
  16. 异步fifo的Verilog实现
  17. 误删除innodb ibdata数据文件 文件句柄 文件描述符 proc fd
  18. 分享一套简单的CodeSmith三层模板
  19. C# FileSystemWatcher 在监控文件夹和文件时的用法
  20. Excel-字符串连接

热门文章

  1. Java从内存流中读取byte数组
  2. JavaScript 第六章总结: Getting to know the DOM
  3. Getting started with Processing 第九章总结
  4. 图像识别 | AI在医学上的应用 | 深度学习 | 迁移学习
  5. hdu-2639 Bone Collector II 背包第K优
  6. 邂逅明下 HDU - 2897
  7. [PAT]数字分类
  8. hdu-6333-莫队
  9. sonar-gerrit plugin配置
  10. 用javascript切换bootstrap的tab