LoginSignup
38
39

More than 5 years have passed since last update.

Swiftの継承についての簡単な整理

Last updated at Posted at 2014-08-12

プロトコルのイニシャライザとクラスのイニシャライザ

前回に続いて、クラスMySuperにクラス自身のイニシャライザを追加してみた。
protocolで宣言したイニシャライザinit(srt)は、修飾子requiredが必要となる。

MySuper.swift
import Foundation

class MySuper:MyProtocol{
    //プロトコルに宣言したinit(str)
    required init(str: String) {
        NSLog("MySuperクラスのrequired init(%@)", str)
    }
    //デフォルトのイニシャライザinit()
    init()
    {
        NSLog("MySuperクラスのデフォルトinit()")
    }

    func protocolFunction01() {
        NSLog("MySuperクラスのFunction01")
    }

    func protocolFunction02() {
        NSLog("MySuperクラスのFunction02")
    }
}

そこで、さらに子クラスMyParentを作ってみる。

余談だが、下記のエラーが起きる。

Overriding declaration requires an 'override' keyword

スクリーンショット 2014-08-12 23.42.47.png

どうやらoverride修飾子が必要なようである。
そこで、適切にoverride修飾子を付加してあげる。

MyParent.swift
import Foundation

class MyParent: MySuper{
    required init(str: String)
    {
        super.init(str: str)
        NSLog("MyParentクラスのrequired init(%@)", str)
    }

    override init()
    {
        super.init()
        NSLog("MyParentクラスのoverride init()")
    }
}

クラスのインスタンス化

ここでいよいよViewControllerで、MyParentクラスをインスタンス化してみる。

ViewController.swift
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var myParent:MyParent = MyParent()

    }
}

コンソール結果は思った通りの結果に。

スクリーンショット 2014-08-13 0.09.40.png

ちなみに、Stringをパラメータとするinit(str)で初期化する場合。

ViewController.swift
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var myParent:MyParent = MyParent(str: "ほげほげ")

    }
}

スクリーンショット 2014-08-13 0.21.28.png
コンソール結果は、2段ほげほげ。

さらに、さらに子クラスMyChildを作ってみる。

MyChild.swift
import Foundation

class MyChild: MyParent{
    required init(str: String)
    {
        super.init(str: str)
        NSLog("MyChildクラスのrequired init(%@)", str)
    }

    override init()
    {
        super.init()
        NSLog("MyChildクラスのoverride init()")
    }
}
ViewController.swift
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //var myParent:MyParent = MyParent(str: "ほげほげ")
        var myChild:MyChild = MyChild(str: "ふがふが")

    }
}

コンソール結果は、3段ふがふが。

スクリーンショット 2014-08-13 0.27.43.png

ここまでは予想通り。w

38
39
0

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
38
39