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
 
 

swiftlint 你所要知道的所有!!的更多相关文章

  1. 你所不知道的setInterval

    在你所不知道的setTimeout记载了下setTimeout相关,此篇则整理了下setInterval:作为拥有广泛应用场景(定时器,轮播图,动画效果,自动滚动等等),而又充满各种不确定性的这set ...

  2. 你所不知道的setTimeout

    JavaScript提供定时执行代码的功能,叫做定时器(timer),主要由setTimeout()和setInterval()这两个函数来完成.它们向任务队列添加定时任务.初始接触它的人都觉得好简单 ...

  3. 你真的会玩SQL吗?你所不知道的 数据聚合

    你真的会玩SQL吗?系列目录 你真的会玩SQL吗?之逻辑查询处理阶段 你真的会玩SQL吗?和平大使 内连接.外连接 你真的会玩SQL吗?三范式.数据完整性 你真的会玩SQL吗?查询指定节点及其所有父节 ...

  4. 你所不知道的linq(二)

    上一篇说了from in select的本质,具体参见你所不知道的linq.本篇说下from...in... from... in... select 首先上一段代码,猜猜结果是什么? class P ...

  5. 【转】你所不知道的Android Studio调试技巧

    这篇写Android studio debug技巧个人觉得写得不错,转自:http://www.jianshu.com/p/011eb88f4e0d# Android Studio目前已经成为开发An ...

  6. Android Service完全解析,关于服务你所需知道的一切(下)

    转载请注册出处:http://blog.csdn.net/guolin_blog/article/details/9797169 在上一篇文章中,我们学习了Android Service相关的许多重要 ...

  7. Android Service完全解析,关于服务你所需知道的一切(上)

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/11952435 相信大多数朋友对Service这个名词都不会陌生,没错,一个老练的A ...

  8. SwiftLint——Swift代码检查及自动格式化工具

    某软不给力,正在做的UWP项目停工了.官方说法是要等到RS2发布新的VOIP架构,再看看是不是给某软面子.虽然Beta用户中发出了几点愤怒的声音,但是木有用.有用的只能是某软的Skype for bu ...

  9. 你所不知道的SQL Server数据库启动过程,以及启动不起来的各种问题的分析及解决技巧

    目前SQL Server数据库作为微软一款优秀的RDBMS,其本身启动的时候是很少出问题的,我们在平时用的时候,很少关注起启动过程,或者很少了解其底层运行过程,大部分的过程只关注其内部的表.存储过程. ...

随机推荐

  1. DirectX之顶点法线的计算

    首先要明白,顶点法线存在的原因:确定灯光照射到物体表面的角度.所以一提到顶点法线,肯定要进行与灯光相关的运算了. 下面是顶点法线的计算方式 假如 A.B.C三个顶点构成一个三角形,它们对应的顶点法线分 ...

  2. nodejs通过request请求远程url的文件并下载到本地

    需要循环去下载远程文件,然后自己写了一个demo,可以直接运行,如下: //文件下载 var fs = require("fs"); var path = require(&quo ...

  3. 十分钟带你理解Kubernetes核心概念

    什么是Kubernetes? Kubernetes(k8s)是自动化容器操作的开源平台,这些操作包括部署,调度和节点集群间扩展.如果你曾经用过Docker容器技术部署容器,那么可以将Docker看成K ...

  4. Abstract Class 一些要点

    抽象类不能使用new operator创建实例. 抽象方法无需实现即可定义.其实现由子类完成. 包含抽象方法的类必须被定义成抽象的. 抽象类的构造函数可以定义成protected,因为它只会被子类使用 ...

  5. 雷林鹏分享:XML 应用程序

    XML 应用程序 本章演示一些基于 XML, HTML, XML DOM 和 JavaScript 构建的小型 XML 应用程序. XML 文档实例 在本应用程序中,我们将使用 "cd_ca ...

  6. p2725 Stamps

    背包. #include <iostream> #include <cstdio> #include <cmath> #include <algorithm& ...

  7. hdu-2089 不要62 基础DP 模板

    http://acm.hdu.edu.cn/showproblem.php?pid=2089 数位DP的思想时预处理以x开头长度为len的数(例如 x000~x999)的所有情况.给出一个数,可以在l ...

  8. CF-825E Minimal Labels 反向拓扑排序

    http://codeforces.com/contest/825/problem/E 一道裸的拓扑排序题.为什么需要反向拓扑排序呢?因为一条大下标指向小下标的边可能会导致小下标更晚分配到号码,导致字 ...

  9. 2.3 UML活动图

    活动图定义 活动图描述了在一个过程中,顺序的/并行的活动及其之间的关系 应用于商业过程.工作流(业务过程).复杂算法的建模 活动图是顶点和弧的集合 活动节点 动作 流 对象值 注解和约束等 活动图基本 ...

  10. 惊世骇俗的sql语句之连表查询

    select `product_skus`.id as skuId, `wname` as sku名称, if(`sku_attributes`.`status`=1,'上架','下架') as 状态 ...