Overriding a stored property in Swift Ask Question

Overriding a stored property in Swift Ask Question

I noticed that the compiler won't let me override a stored property with another stored value (which seems odd):

class Jedi {
    var lightSaberColor = "Blue"
}


class Sith: Jedi {
    override var lightSaberColor = "Red" // Cannot override with a stored property lightSaberColor
}

However, I'm allowed to do this with a computed property:

class Jedi {
    let lightSaberColor = "Blue"
}


class Sith: Jedi {
    override var lightSaberColor : String{return "Red"}

}

Why am I not allowed to give it another value?

Why is overriding with a stored property an abomination and doing it with a computed one kosher? What where they thinking?

ベストアンサー1

Why am I not allowed to just give it another value?

継承したプロパティに異なる値を与えることは間違いなく許可されています。その初期値を受け取るコンストラクターでプロパティを初期化し、派生クラスから異なる値を渡すと、それが可能になります。

class Jedi {
    // I made lightSaberColor read-only; you can make it writable if you prefer.
    let lightSaberColor : String
    init(_ lsc : String = "Blue") {
        lightSaberColor = lsc;
    }
}

class Sith : Jedi {
    init() {
        super.init("Red")
    }
}

let j1 = Jedi()
let j2 = Sith()

print(j1.lightSaberColor)
print(j2.lightSaberColor)

プロパティをオーバーライドすることは、新しい値を与えることとは異なります。クラスに別のプロパティを与えるようなものです。実際、計算プロパティをオーバーライドすると、それが起こります。基本クラスのプロパティを計算するコードは、交換された派生クラスでそのプロパティのオーバーライドを計算するコードによって。

実際に保存されたプロパティをオーバーライドすること、つまりlightSaberColor他の動作をさせることは可能ですか?

オブザーバーを除き、保存されたプロパティには動作がないため、オーバーライドするものは実際にはありません。プロパティに別の値を与えることは、上記のメカニズムを通じて可能です。これは、質問の例が実現しようとしていることとまったく同じことを、異なる構文で実現します。

おすすめ記事