LoginSignup
3
2

More than 5 years have passed since last update.

swift4で"子クラスに"プロトコルを準拠させる方法

Last updated at Posted at 2019-01-14

特定のクラスにプロトコルを準拠させるのではなく、その子クラスにプロトコルを準拠させたいことがあったのでメモまでに!

コード例

例えばUITableViewCellクラスを継承する独自cellのクラスに、identifierというstaticプロパティを持たせたいとします。

// 対象の独自cellクラス(子クラス)
class ShopListViewCell: UITableViewCell {}

// Protocolを用意
protocol IdentifiedCell {}

// まずUITableViewCell(親クラス)を準拠させる
extension UITableViewCell: IdentifiedCell {}

// 子クラスに準拠させたいProtocol内容を記述
extension IdentifiedCell where Self: UITableViewCell {

    // `Self`が使えるのがいいですね!
    static var identifier: String {
        return String(describing: Self.self) // => "ShopListViewCell" など子クラスの名前取得できる
    }
}

※Protocolエクステンションであるため、ストアドプロパティを定義できないのは仕方ないですね😅

まとめ

簡単にいうと、親クラスに準拠させたプロトコルに、extensionでwhere Self: 親クラスという形で子クラスにのみ対応させたい内容を追加していけばいいんですね🙌
よければ使ってみてください!
他にもいい方法があればコメントお待ちしてます〜〜

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