0
1

More than 1 year has passed since last update.

【Swift】プロトコルを拡張して実装を任意化する

Posted at

通常

import UIKit

class ViewController: UIViewController, SampleDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .red
    }
    func sample() {
        print("サンプル")
    }
}

protocol SampleDelegate {
    func sample()
}

sample()を実装しないと下の画像のようにXcodeに怒られます
スクリーンショット 2022-10-16 18.28.31.png

デフォルト実装

import UIKit

class ViewController: UIViewController, SampleDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .red
    }
}

protocol SampleDelegate {
    func sample()
}

extension SampleDelegate {
    func sample() {}
}

extensionで実装しておく事によってプロトコルを準拠させても任意で実装することができます。
スクリーンショット 2022-10-16 18.30.04.png

おまけ

こんなこともできるみたいです。
あんまり理解してないです笑
なんとなく分かったら別で記事に書こうと思います。

import UIKit

class ViewController: UIViewController, SampleDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .red
    }
}

@objc protocol SampleDelegate {
    @objc optional func sample()
}

スクリーンショット 2022-10-16 18.37.05.png

おわり

プロトコル使いこなしてゴリゴリ使っていきたいです

0
1
2

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