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

  某软不给力,正在做的UWP项目停工了。官方说法是要等到RS2发布新的VOIP架构,再看看是不是给某软面子。虽然Beta用户中发出了几点愤怒的声音,但是木有用。有用的只能是某软的Skype for business UWP版拿下几个大订单,才有说服力。像现在这样鶸的表现,真是让人心寒……

  当然UWP开发入门还会继续写下去,本篇只是偷个懒,把工作中整理的资料放上来。蜀黍我可不是叛徒,我没发过誓不给水果开发APP,某软现在就是最大的果蛆。无奈混口饭吃,让写Swift就写呗,水果一套加上Xcode,咋用咋不爽,跟太阳系最强IDE比实在差距有点大,不得已还得额外安装代码格式检查的工具,安装过程也是学习使用MacOS,Terminal一系列陌生玩意的痛苦经历,风格迥异让我生不如死。特地写此一篇备忘,及供和我一样的iOS鶸参考。

What can SwiftLint do?

  1. Give code style warnings and errors 
  2. Auto format swift code file

Installation

  • You can also install SwiftLint by downloading SwiftLint.pkg from the latest GitHub release and running it.

Integrate SwiftLint into an Xcode scheme to get warnings and errors displayed in the IDE.

In project file, just add a new "Run Script Phase" with:

if which swiftlint >/dev/null; then
  swiftlint
else
  echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi

Warnings and errors

Build project , swiftlint will display warnings and errors in Xcode.

We can disable or create some rules in configuration file.

Swiftlint Auto Correct

For formatting code files, you need to input "swiftlint autocorrect" in terminal.

cd documents/projects/MyProject/SomeFolder
swiftlint autocorrect

If you want to lint only one file:

cd documents/projects/MyProject/SomeFolder
swiftlint autocorrect --path SampleCode.swift

Unformatted:

Formatted:

Download Swift Configuration File

You can download swift configuration file in any folder. But the file which name starts with "." will be hidden on MacOS.

So I suggest you create an new file ".swiftlint.yml" in Xcode, under your project root folder.

Input below in terminal

cd documents/projects/yourProjectName
curl https://raw.githubusercontent.com/kevindelord/swift-style-guide/master/.swiftlint.yml > .swiftlint.yml

Press enter button and download. Then you can get lateset .swiftlint.yml and edit in Xcode.

Disable, included or create custom rule in .swiftlint.yml file

  • Disable rules

Add "- rule name" below "disabled_rules:"

disabled_rules:

  - trailing_whitespace

  • Included folder

Only check child foder with SwiftLint

included:

  - MyProject/NeedCheckFolder

  • Create custom rules 

Use Regular Expression (regex) create custom rules

custom_rules:

  comments_space:

    name: "Space After Comment"

    regex: "(^ *//\w+)"

    message: "There should be a space after //"

    severity: error

  multiple_empty_lines:

    name: "Multiple Empty Lines"

    regex: ".\n(\s*\n){2,}"

    message: "There are too many line breaks"

References

https://github.com/realm/SwiftLint

http://kevindelord.io/2016/04/06/integrate-swiftlint/

https://swifting.io/blog/2016/03/29/11-swiftlint/

 

posted @ 2016-08-16 22:46  楼上那个蜀黍  阅读(4819)  评论(0编辑  收藏  举报