LoginSignup
44
31

More than 5 years have passed since last update.

[SwiftLint]コードの中で無効にするルールを指定する

Posted at

SwiftLintの記事もこれで最後になるかと思います。
仕上げはDisable a rule in codeです。

コード中で無効にするルールを指定する

disable-enable

基本的には.swiftlint.ymlの中で無効にするルールの記述をしますが、コード中のコメントで指定することもできます。
フォーマットは以下の通りです。

// swiftlint:disable <ルール名>

これによって無効にしたルールは、以下のルールを有効にするフォーマットの記述が現れるまで適用されます。

// swiftlint:enable <ルール名>

よって、以下のようになります(例文自体は公式から抜粋)。

// swiftlint:disable colon
let noWarning :String = "" // No warning about colons immediately after variable names!
// swiftlint:enable colon
let hasWarning :String = "" // Warning generated about colons immediately after variable names

スクリーンショット 2016-01-23 14.07.54.png

※ちなみにルールに沿った書き方にして警告を解消する場合は
let hasWarning: String = ""
にすればいいですね。

next, this, previous

もう一つルールの無効/有効の設定をする方法として、:previous, :this, :nextを使う方法があります。
これを用いると、前の行、今の行、次の行限定でルールを無効/有効にすることができます。
下の例では前、今、次の行でforce_castを無効にしています。

// swiftlint:disable:next force_cast
let noWarning = NSNumber() as! Int
let hasWarning = NSNumber() as! Int
let noWarning2 = NSNumber() as! Int // swiftlint:disable:this force_cast
let noWarning3 = NSNumber() as! Int
// swiftlint:disable:previous force_cast

スクリーンショット 2016-01-23 15.04.00.png

有効にする方法も同様です。

// swiftlint:enable:next force_cast
let noWarning = NSNumber() as! Int
let hasWarning = NSNumber() as! Int

スクリーンショット 2016-01-23 15.19.43.png

複数指定

例えばある1行に対して2つdisableにしたいとします。その時はどのように書けば良いのでしょうか。
公式のREADMEには特に何も書かれていないのでちょっと調べてみました。

コード上で
// swiftlint:disable:next colon, line_length
// swiftlint:disable:next colon:line_length
などとやってみるものの、期待する結果は得られませんでした。

そこでCommand.swiftを見てみると、1行で複数のルールをdisableにすることは厳しそうな雰囲気が出てきました。
なので1行であろうと、おそらくこのように指定するのが現状の解決策なのではないかと思います。

// swiftlint:disable colon
// swiftlint:disable line_length
let noWarning :String = "" // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
// swiftlint:enable line_length
// swiftlint:enable colon
44
31
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
44
31