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/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM