LoginSignup
1
2

More than 1 year has passed since last update.

[Swift]継承が必要な処理ごとにextensionでコードを分ける

Last updated at Posted at 2021-04-30

extensionで拡張する

一つのclassでいくつも継承すると、コードを読む時にどこで拡張機能を使用しているのか分かりにくい。
そこで、継承が必要な処理ごとにextensionでclassを拡張し、処理を分けることで
どの処理が準拠しているのかを分かりやすくする:point_up:

class HogeViewController: UIViewController {
    ~~~
}

extension HogeViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

textFieldShouldReturnはUITextFieldDelegateを継承しないと使えないので
今回はextensionでHogeViewControllerを拡張し、そこで継承が必要な処理をまとめている:hugging::sparkles:

もちろん、class宣言時にまとめて

class HogeViewController: UIViewController, UITextFieldDelegate {
    ~~~~~
}

って書いても問題はない:ok_woman:

でも、継承するもので処理を分けた方がコードを読む時に分かりやすいのでextensionで拡張する方がいい。
(例の状態だとピンとこないかもしれないが、継承先が3個以上とかになった場合に、どの処理で何から継承したメソッドを使っているのかが分かりづらくなる。)

注意点

拡張したHogeViewControllerの方でUITextFieldDelegateを継承していれば、
元のclassの方のHogeViewControllerでもUITextFieldDelegateに準拠したメソッドを使うことができる。

class HogeViewController: UIViewController {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

extension HogeViewController: UITextFieldDelegate {
}

その為、本来継承が必要な処理をextensionではなく元のclassの方で使用していても、問題なく動作してしまう。そうすると逆に可読性が下がるかもしれないので注意が必要:thinking:

1
2
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
1
2