LoginSignup
42
19

More than 3 years have passed since last update.

プロパティやメソッドの並び順テンプレート(Swift)

Last updated at Posted at 2019-12-08

はじめに

SwiftLintには、クラスやプロパティなどの並び順を強制するルールがあります。

ルール名 概要
file_types_order ファイル内の型の並び順を強制する
type_contents_order 型内のプロパティやメソッドの並び順を強制する

これらのルールを適用することで、必然的にコードが整理されて可読性が上がります。

しかし、並び順を覚えるのは大変です。
ぱっと見でどこに何を書けば(書いてあるか)わかるよう、テンプレートを作成しました。

ルールの例からほぼ変えていないので、公式を見るだけでもいいと思います。
https://github.com/realm/SwiftLint/blob/0.38.0/Rules.md#file-types-order
https://github.com/realm/SwiftLint/blob/0.38.0/Rules.md#type-contents-order

自分ルール

同じグループの場合、アクセス修飾子の大きいものから順に書きます。
( openpublicinternalfileprivateprivate )

アクセス修飾子も同じ場合、読み下しやすい順に書きます。

class TestViewController: UIViewController {

    // MARK: Other Methods

    // privateよりinternalメソッドから先に書く
    func hoge() {}

    // 呼び出し側から先に書くと読み下しやすい
    private func foo() {
        bar()
    }

    private func bar() { }
}

準拠したプロトコルのメソッドは、 // MARK: {プロトコル名} としてOther Methodsの上に書きます。

// MARK: Protocols

protocol TestViewControllerDelegate: AnyObject {
    func didPressTrackedButton()
}

// MARK: Main Type

class TestViewController: UIViewController, TestViewControllerDelegate {

    // MARK: TestViewControllerDelegate

    func didPressTrackedButton() {
        // some code
    }

    // MARK: Other Methods

}

環境

  • SwiftLint:0.38.0

テンプレート

// MARK: Protocols

protocol TestViewControllerDelegate: AnyObject {
    func didPressTrackedButton()
}

// MARK: Main Type

class TestViewController: UIViewController, TestViewControllerDelegate {

    // MARK: Type Aliases

    // MARK: Classes

    // MARK: Structs

    // MARK: Enums

    // MARK: Stored Type Properties

    // MARK: Stored Instance Properties

    // MARK: Computed Instance Properties

    // MARK: IBOutlets

    // MARK: Initializers

    // MARK: Type Methods

    // MARK: View Life-Cycle Methods

    // MARK: IBActions

    // MARK: TestViewControllerDelegate

    // MARK: Other Methods

    // MARK: Subscripts

}

// MARK: Extensions

extension TestViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
}

おわりに

Xcode上で新しくファイルを追加したら、まず上記のコメントをコピペするのがオススメです。
コーディング後、未実装のグループのコメントを削除すると見通しがよくなります。

42
19
0

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
42
19