Skip to content

Instantly share code, notes, and snippets.

@k-motoyan
Created February 3, 2017 14:40
Show Gist options
  • Save k-motoyan/888832d3ce23767143951c2f3ad860db to your computer and use it in GitHub Desktop.
Save k-motoyan/888832d3ce23767143951c2f3ad860db to your computer and use it in GitHub Desktop.
ジェネリクスを使ってDelegateの振る舞いを変更する
// Delegate用Protocol
protocol RequestDelegate : class {
func begin()
func done()
}
// APIリクエストクラス
class Request {
weak var delegate: RequestDelegate?
func call() {
delegate?.begin()
delegate?.done()
}
}
// APIリクエストを行うViewController
class MyViewController<T>: UIViewController, RequestDelegate {
private var request: Request?
override func viewDidLoad() {
super.viewDidLoad()
// リクエストクラスをメンバ変数に保持して、Delegate先に自身を設定
request = Request()
request.delegate = self
}
func apiCall() {
requst.call()
}
}
// MyViewControllerのサブタイプ
class NewMyView {}
// Delegate処理の実装
extension RequestDelegate {
func begin() {
print("request begin.")
}
func done() {
print("request done.")
}
}
extension RequestDelegate where Self: MyViewController<NewMyView> {
func begin() {
print("new begin.")
}
func done() {
print("new done.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment