LoginSignup
249
164

More than 5 years have passed since last update.

SwiftLintのRules全まとめ

Last updated at Posted at 2017-02-14

SwiftLintのRulesをメモがてら簡単にまとめました.警告が出る例を示したスクショつきです.SwiftLintの導入方法や.swiftlint.ymlの構文については解説しません.

defaultopt-in毎にidentifierのアルファベット順になっているはずです.ところどころうまく警告を出すことができず(?)画像がないですが,ご容赦ください.

蛇足ですが,Rules一覧については次のコマンドで大まかに確認することもできます.

$ swiftlint rules

default

class_delegate_protocol

Class Delegate Protocol:
Delegate protocols should be class-only so they can be weakly referenced.

Delegate Protocol(名前の末尾がDelegateとなるProtocol)はweakで保持される可能性があるため,class-onlyなProtocolであるべき.

class_delegate_protocol.png

closing_brace

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

}の後に)が続く場合,それらの間に空白があるべきでない.

closing_brace.png

closure_parameter_position

Closure Parameter Position:
Closure parameters should be on the same line as opening brace.

クロージャの引数リストはクロージャの始まり{と同じ行にあるべき.

closure_parameter_position.png

colon

Colon:
Colons should be next to the identifier when specifying a type and next to the key in dictionary literals.

:は変数名の直後に書き,型名はその後に1スペース開けて書くべき.また,Dictionaryではkeyの直後に:を書き,valueはその後に1つのスペースを開けて書くべき.

colon.png

comma

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

,の前にはスペースを入れず,,の後には1つのスペースを入れる.

comma.png

compiler_protocol_init

Compiler Protocol Init: 
The initializers declared in compiler protocols such as `ExpressibleByArrayLiteral
 shouldn't be called directly.

リテラルを直接書き並べて初期化するタイプのinitializerは直接呼び出すべきではない.

compiler_protocol_init.png

control_statement

Control Statement: 
if,for,while,do statements shouldn't wrap their conditionals in parentheses.

if等の制御文の条件式部分は( )で囲むべきでない.

control_statement.png

custom_rules

Custom Rules: 
Create custom rules by providing a regex string.  Optionally specify what syntax kinds to match against, the severity level, and what message to display.

.siwftlint.ymlに記述されたcustome_rulesを実行する.

画像省略

cyclomatic_complexity

Cyclomatic Complexity: 
Complexity of function bodies should be limited.

関数内の複雑性(ネストの深いifやifの連続)は程々に

cyclomatic_complexity.png

discarded_notification_center_observer

Discarded Notification Center Observer: 
When registing for a notification using a block, the opaque observer that is returned should be stored so it can be removed later.

NotificationCenter.addObserver(forName:object:queue:using:)で追加されたobserverは後で除去できるように変数に格納して保持するべき.

discarded_notification_center_observer.png

dynamic_inline

Dynamic Inline: 
avoid using 'dynamic' and '@inline(__always)' together.

@inline指定とdynamicを同時に使わない.

dynamic_inline.png

empty_parameters

Empty Parameters: 
Prefer `() -> ` over `Void -> `.

関数の引数がない時,Void ->でなく() ->を用いる.

empty_parameters.png

empty_parentheses_with_trailing_closure

Empty Parentheses with Trailing Closure: 
When using trailing closures, empty parentheses should be avoided after the method call.

末尾クロージャを使用するときはメソッド名の後に引数のない空の()は書くべきでない.

empty_parentheses_with_trailing_closure.png

file_length

File Line Length: 
Files should not span too many lines.

ファイルの行数は多くなりすぎないように.
デフォルトだと401行で警告が出ます.

file_length.png

force_cast

Force Cast:
Force casts should be avoided.

強制キャスト(as!)は避けるべき.

force_cast.png

force_try

Force Try:
Force tries should be avoided.

try!の使用は避けるべき.

force_try.png

for_where

For Where:
`where` clauses are preferred over a single `if` inside a `for`.

for文において,その内部でifによる値チェック処理しかしないのであればwhere句を使用する.

for_where.png

function_body_length

Function Body Length:
Functions bodies should not span too many lines.

関数の行数はあまり多くなりすぎないように.
デフォルトだと41行で警告が出るはず…ですが,何も出ませんでした.画像省略.

function_parameter_count

Function Parameter Count:
Number of function parameters should be low.

関数の引数は少なく.
デフォルトだと6個で警告が出ます.

function_parameter_count.png

generic_type_name

Generic Type Name:
Generic type name should only contain alphanumeric characters start with an uppercase character and span between 1 and 20 characters in length.

ジェネリクスの型名は大文字のアルファベットから初めて,英数字のみを含み,かつ1〜20文字の長さにするべき.

generic_type_name.png

identifier_name

Identifier Name:
Identifier names should only contain alphanumeric characters and start with a lowercase character or should only contain capital letters.  In an exception to the above, variable names may start with a capital letter when they are declared static and immutable. Variable names should not be too long or too short.

旧variable_name

変数名等の識別子は小文字で始まるか全て大文字の英数字だけで構成させるべき.長さは短すぎず,長すぎず.
デフォルトだと2文字で少ないよという警告,41文字で多いよという警告が出ます.

identifier_name.png

implicit_getter

Implicit Getter:
Computed read-only properties should avoid using the get keyword.

read-onlyな計算プロパティはgetキーワードを書くべきでない.

implicit_getter.png

large_tuple

Large Tuple:
Tuples shouldn't have too many members. Create a custom type instead.

タプルのメンバは少なめに.多くなるようならユーザ定義型を用いる.
デフォルだと3メンバで警告が出るはず…ですが,何も出ませんでした.画像省略.

leading_whitespace

Leading Whitespace:
Files should not contain leading whitespace.

ファイルの先頭に空白類文字を含むべきでない.

leading_whitespace.png

legacy_cggeometry_functions

Legacy CGGeometry Functions:
Struct extension properties and methods are preferred over legacy functions

CGRect系のレガシーなメソッド(CGRectGetWidth(rect)とか)は用いずにextensionのプロパティやメソッド(CGRect.width)を用いる.

Swift3系では既にリプレースされているため出くわす場面はなさそうです.

legacy_constant

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

レガシーなglobalスコープの定数(CGRectZeroとか)よりも各種構造体スコープの定数(CGRect.zero)を用いる.

こちらもSwift3系においてはリプレースされています.

legacy_constructor

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

レガシーなコンビニエンスメソッド(CGRectMake()とか)よりもコンストラクタを用いる.

同上.

legacy_nsgeometry_functions

Legacy NSGeometry Functions:
Struct extension properties and methods are preferred over legacy functions

レガシーなNSRect系の関数(NSWidth()とか)よりもextensionのプロパティやメソッド(NSRect.width)を用いる.

legacy_nsgeometry_functions.png

line_length

Line Length:
Lines should not span too many characters.

1行における文字数は多くなりすぎないように.
デフォルトだと121文字で警告が出ます.

line_length.png

mark

Mark:
MARK comment should be in valid format.

MARKコメントは正しいフォーマットで書くべき.

mark.png

nesting

Nesting:
Types should be nested at most 1 level deep, and statements should be nested at most 5 levels deep.

ネスト型は深くても1レベルの深さまで,その他の文は深くても5レベルの深さまでのネストに留めるべき.

nesting1.png

nesting2.png

notification_center_detachment

Notification Center Detachment:
An object should only remove itself as an observer in `deinit`.

NSNotificationCenterに登録したobserverはクラスのdeinit内で除去するべき.

特に警告が発生しなかったので画像省略.

opening_brace

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

関数等の開き{は直前に1つのスペースを置いてから書き,なおかつ宣言と同じ行に書くべき.

opening_brace.png

operator_whitespace

Operator Function Whitespace:
Operators should be surrounded by a single whitespace when defining them.

演算子を定義する際は演算子の前後に1つのスペースを置くべき.

operator_whitespace.png

private_unit_test

Private Unit Test:
Unit tests marked private are silently skipped.

privateなテストケースメソッドは書かない.

private_unit_test.png

redundant_discardable_let

Redundant Discardable Let:
Prefer `_ = foo()` over `let _ = foo()` when discarding a result from a function.

関数の返り値を読み捨てる際にletはわざわざ書かない.

特に警告が発生しなかったので画像省略.

redundant_optional_initialization

Redundant Optional Initialization:
Initializing an optional variable with nil is redundant.

オプショナル変数宣言時のnil初期化は冗長なため,書くべきでない.

特に警告が発生しなかったので画像省略.

redundant_string_enum_value

Redundant String Enum Value:
String enum values can be omitted when they are equal to the enumcase name.

String型のenumの各caseの値をcase名と同じにする際は,その処理は省略できるので書かない.

redundant_string_enum_value.png

redundant_void_return

Redundant Void Return:
Returning Void in a function declaration is redundant.

Voidを返す関数の宣言時に-> Voidを書くのは冗長なため,書かない.

redundant_void_return.png

return_arrow_whitespace

Returning Whitespace:
Return arrow and return type should be separated by a single space or on a separate line.

関数の返り値を指定する->と型名は,それぞれ1つのスペースで区切られるか,別の行に書くべき.

return_arrow_whitespace.png

shorthand_operator

Shorthand Operator:
Prefer shorthand operators (+= -= *= /=) over doing the operation and assigning.

複号代入演算子をなるべく使う.

shorthand_operator.png

statement_position

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

else節やcatch節は直前の}の後に1つのスペースを置き,同じ行に書くべき.

statement_position_default.png

OR

Statement Position:
Else and catch should be on the next line with equal indentation to the previous declaration.

else節やcatch節は直前の}の後に改行し,同じインデントを揃えて書くべき.

statement_position_uncuddled.png

これらは.swiftlint.ymlに次のようにオプションを書くことで切り替えられます.

.swiftlint.yml
statement_position:
    statement_mode: uncuddled_else

C#スタイルのelse節の書き方をuncuddledって呼称するんですね… 初知りです.

syntactic_sugar

Syntactic Sugar:
Shorthand syntactic sugar should be used i.e. [Int] instead of Array<Int>

糖衣構文を使うべき.

syntactic_sugar.png

todo

Todo:
TODOs and FIXMEs should be avoided.

TODOおよびFIXMEコメントは避けるべき.

todo.png

trailing_comma

Trailing Comma:
Trailing commas in arrays and dictionaries should be avoided/enforced.

ArrayやDictionary中の末尾の,は避ける/強制すべき.

とにかく末尾コンマ書かないVer.

trailing_comma_default.png

複数行になるとき末尾コンマ強制するVer.

trailing_comma_mandatory.png

これらは.swiftlint.ymlに次のようにオプションを書くことで切り替えられます.trueのとき強制モードになります.

.swiftlint.yml
trailing_comma:
    mandatory_comma: true

trailing_newline

Trailing Newline:
Files should have a single trailing newline.

各ファイルは末尾に空行を1行だけ持つべき.

trailing_newline.png

trailing_semicolon

Trailing Semicolon:
Lines should not have trailing semicolons.

各行の末尾にセミコロンは書くべきでない.

trailing_semicolon.png

trailing_whitespace

Trailing Whitespace:
Lines should not have trailing whitespace.

各行の末尾に空白類文字を書くべきでない.

trailing_whitespace.png

スペースがいくつか入っています.

type_body_length

Type Body Length:
Type bodies should not span too many lines.

型の本体の行数は多くなりすぎないように.
デフォルトだと201行で警告が出ます.

type_body_length.png

type_name

Type Name:
Type name should only contain alphanumeric characters start with an uppercase character and span between 3 and 40 characters in length.

型名は大文字アルファベットで始まる英数字だけで構成され,かつ3~40文字であるべき.

type_name.png

unused_closure_parameter

Unused Closure Parameter:
Unused parameter in a closure should be replaced with _.

使用されないクロージャの引数は_で置き換えるべき.

unused_closure_parameter.png

unused_enumerated

Unused Enumerated:
When the index or the item is not used `.enumerated()` can be removed.

for文でindexないしは要素が使用されないときは.enumerated()の記述は除去できるので除去すべき.

警告が出なかったので画像省略.

unused_optional_binding

Unused Optional Binding:
Prefer `!= nil` over `let _ =`

let _ =によるOptional Bindingよりは!= nilでOptional判定したほうが良い.

Screen Shot 2017-04-15 at 1.22.41 PM.png

valid_ibinspectable

Valid IBInspectable:
@IBInspectable should be applied to variables only have its type explicit and be of a supported type.

@IBInspectable属性は明示的な型を持った変数とサポートされた型にのみ用いるべき.

valid_ibinspectable.png

vertical_parameter_alignment

Vertical Parameter Alignment:
Function parameters should be aligned vertically if they're in multiple lines in a declaration.

関数の引数を複数行に分けて書く際はそのアラインメントを揃えるべき.

vertical_parameter_alignment.png

vertical_whitespace

Vertical Whitespace:
descriptionReason

空行は1行に抑えるべき.

vertical_whitespace.png

void_return

Void Return:
Prefer `-> Void` over `-> ()`.

-> ()よりは-> Voidを用いる.

void_return.png

weak_delegate

Weak Delegate:
Delegates should be weak to avoid reference cycles.

循環参照を避けるため,Delegateweakで保持されるべき.

weak_delegate.png

opt-in

attributes

Attributes:
Attributes should be on their own lines in functions and types, but on the same line as variables and imports.

@discardableResultなどの属性は宣言された関数・型の直前の行にあるべき.変数やimportが続く場合は同じ行にあるべき.

attributes.png

closure_end_indentation

Closure End Indentation: 
Closure end should have the same indentation as the line that started it.

クロージャの閉じ}はクロージャが始まった行と同じインデントであるべき.

closure_end_indentation.png

closure_spacing

Closure Spacing:
Closure expressions should have a single space inside each brace.

クロージャ内の式はカッコの間に1つのスペースがあるべき.

closure_spacing.png

conditional_returns_on_newline

Conditional Returns on Newline:
Conditional statements should always return on the next line

条件文は始まった行の次の行でreturnするべき.

conditional_returns_on_newline.png

empty_count

Empty Count: 
Prefer checking `isEmpty` over comparing `count` to zero.

要素が何もないことを確認する際はcount == 0よりもisEmptyを用いてチェックする.

empty_count.png

explicit_init

Explicit Init: 
Explicitly calling .init() should be avoided.

明示的な.init()メソッドの呼び出しは避けるべき.

explicit_init.png

file_header

File Header: 
Files should have consistent header comments.

各ファイルは一貫性のあるヘッダコメントを持つべき..swiftlint.ymlで含むべき文字列などを指定できます.

file_header.png

first_where

First Where: 
Prefer using `.first(where:)` over `.filter { }.first` in collections.

.filter { }.firstよりも.first(where:)を用いる.

first_where.png

force_unwrapping

Force Unwrapping:
Force unwrapping should be avoided.

強制アンラップは避けるべき.

force_unwrapping.png

missing_docs

Missing Docs:
Public declarations should be documented.

publicな宣言はドキュメント化されているべき.

missing_docs.png

nimble_operator

Nimble Operator:
Prefer Nimble operator overloads over free matcher functions.

Nimbleの使用にあたり,free matcher functionsよりもオーバロードされた演算子を用いる.

筆者はNimbleを使用したことがないため,細かいことは書けません.

number_separator

Number Separator:
Underscores should be used as thousand separator in large decimal numbers.

大きな数値を書く際はセパレータ(1_000_000 みたいな)を書くべき.

number_separator.png

object_literal

Object Literal:
Prefer object literals over image and color inits.

イニシャライザを直接呼び出すよりは#imageLiteral#colorLiteralを用いる.

object_literal.png

operator_usage_whitespace

Operator Usage Whitespace:
Operators should be surrounded by a single whitespace when they are being used.

演算子を使用する際は前後に1つのスペースを開けるべき.

operator_usage_whitespace.png

overridden_super_call

Overridden methods call super:
Some overridden methods should always call super

オーバーライドされたメソッドは常にsuperを呼び出すべき.

overridden_super_call.png

private_outlet

Private Outlets:
IBOutlets should be private to avoid leaking UIKit to higher layers.

@IBOutlet変数はprivate修飾するべき.

private_outlet.png

prohibited_super_call

Prohibited calls to super:
Some methods should not call super

いくつかのメソッドにおいてはsuperを呼び出すべきではない.

prohibited_super_call.png

redundant_nil_coalescing

Redundant Nil Coalescing:
nil coalescing operator is only evaluated if the lhs is nil, coalescing operator with nil as rhs is redundant.

nil結合演算子において,左辺がnilの場合のみ評価される性質上,右辺にnilを書くのは冗長なため,書くべきでない.

redundant_nil_coalescing.png

sorted_imports

Sorted Imports:
Imports should be sorted.

import部分はソートされているべき.

sorted_imports.png

switch_case_on_newline

Switch Case on Newline:
Cases inside a switch should always be on a newline

switch文におけるcaseの各処理は改行した後書くべき.

警告が発生しなかったので画像省略.

valid_docs

Valid Docs:
Documented declarations should be valid.

ドキュメントは有効なものであるべき.

画像省略.

参照リポジトリ

249
164
3

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
249
164