通常
import UIKit
class ViewController: UIViewController, SampleDelegate {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
}
func sample() {
print("サンプル")
}
}
protocol SampleDelegate {
func sample()
}
sample()
を実装しないと下の画像のようにXcodeに怒られます
デフォルト実装
import UIKit
class ViewController: UIViewController, SampleDelegate {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
}
}
protocol SampleDelegate {
func sample()
}
extension SampleDelegate {
func sample() {}
}
extension
で実装しておく事によってプロトコルを準拠させても任意で実装することができます。
おまけ
こんなこともできるみたいです。
あんまり理解してないです笑
なんとなく分かったら別で記事に書こうと思います。
import UIKit
class ViewController: UIViewController, SampleDelegate {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
}
}
@objc protocol SampleDelegate {
@objc optional func sample()
}
おわり
プロトコル使いこなしてゴリゴリ使っていきたいです