Created
February 3, 2017 14:40
-
-
Save k-motoyan/888832d3ce23767143951c2f3ad860db to your computer and use it in GitHub Desktop.
ジェネリクスを使ってDelegateの振る舞いを変更する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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