LoginSignup
1
2

More than 5 years have passed since last update.

【swift】delegateを継承して利用する

Last updated at Posted at 2018-09-17

delegateを継承して利用する場合は、継承先のクラスでキャストして利用すれば複数の継承を行っても問題なく利用できます。

import UIKit

class ViewController: UIViewController, DDDDelegate {

    let ddd = DDD()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        ddd.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func printAAA() {
        print("AAA")
    }
    func printBBB() {
        print("BBB")
    }
    func printCCC() {
        print("CCC")
    }
    func printDDD() {
        print("DDD")
    }

    @IBAction func TouchAAA(_ sender: Any) {
        ddd.startAAA()
    }
    @IBAction func TouchBBB(_ sender: Any) {
        ddd.startBBB()
    }
    @IBAction func TouchCCC(_ sender: Any) {
        ddd.startCCC()
    }
    @IBAction func TouchDDD(_ sender: Any) {
        ddd.startDDD()
    }
}
import UIKit

// プロトコル
protocol AAADelegate: class {
    func printAAA()
}

class AAA: NSObject {
    weak var delegate: AAADelegate?

    func startAAA() {
        self.delegate?.printAAA();
    }
}
import UIKit

// プロトコル
protocol BBBDelegate: AAADelegate {
    func printBBB()
}

class BBB: AAA {

    func getDelegate() -> BBBDelegate? {
        return self.delegate as? BBBDelegate
    }

    func startBBB() {
        self.getDelegate()?.printBBB()
    }
}
import UIKit

// プロトコル
protocol CCCDelegate: BBBDelegate {
    func printCCC()
}

class CCC: BBB {

    func getDelegate() -> CCCDelegate? {
        return self.delegate as? CCCDelegate
    }

    func startCCC() {
        getDelegate()?.printCCC();
    }
}
import UIKit

// プロトコル
protocol DDDDelegate: CCCDelegate {
    func printDDD()
}

class DDD: CCC {

    func getDelegate() -> DDDDelegate? {
        return self.delegate as? DDDDelegate
    }

    func startDDD() {
        getDelegate()?.printDDD()
    }
}
1
2
1

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