LoginSignup
4
4

More than 5 years have passed since last update.

Update properties from subclass

Posted at

Swiftでの継承で気をつけること

initializerはデフォルトでは継承されない

サブクラスのを呼び出すときにスーパークラスのinitializerはデフォルトでは見えないので
サブクラスの型で実装してあげる必要がある。ここはObjective-Cと少し違うところらしい。

class SuperClass {
    var value: Int
    init(v: Int) {
        value = v
    }
    func description() -> String {
        return "The values is \(value)"
    }
}

class SubClass: SuperClass {
    init() {
        super.init(v: 3)
        println("This is SubClass's initializer")
    }
}

let c: SubClass = SubClass(v: 4) // ここでエラーになる
c.description()


サブクラスからはvarのみ変更できる

サブクラスからはどの変数も参照できる(publicとかprivateとかアクセス修飾子みたいなものなさそう)が、変更はvarに対してのみ。constant propertyに対しては変更が効かない。

class SuperClass {
    let value: Int  // letにするとSubClassのvalue = 2でエラーになる
    init(v: Int) {
        value = v
    }
    func description() -> String {
        return "The values is \(value)"
    }
}

class SubClass: SuperClass {
    init() {
        super.init()
        value = 2
    }
}
4
4
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
4
4