Hi,
Following my previous post, I have synthesized the rules for overriding a property in the following table:
Why is it that we can't override an immutable stored property with a computed property ?
Swift documentation states that we can override any inherited property.
I know we can't override a property with a stored property (it would duplicate the storage space).
Also, I elaborated on an example to test all the options for overriding a property.
I am not sure if it's correct, would really appreciate some feedback :)
class ClassA {
let constantStoredProperty: String = "Read-Only Behavior"
var mutableStoredProperty: String = "Read-Write Behavior"
var computedPropertyWithGet: String {
get {
return "Read-Only Behavior"
}
}
var computedPropertyWithGetAndSet: String {
get {
return "Read-Write Behavior"
}
set {
// some statements
}
}
}
// overriding the 4 properties of ClassA -----------------------------------
// overriding the first property of Class A - allowed options --------------
// overriding the first property of Class A - not allowed options ----------
// overriding the second property of Class A - allowed options -------------
class ClassI: ClassA {
override var mutableStoredProperty: String {
get {
return "Overriding with Read-Write Computed Property"
}
set {
// some statements
}
}
}
// overriding the second property of Class A - not allowed options ---------
class ClassJ: ClassA {
override var mutableStoredProperty: String {
get {
return "Overriding with Read-Only Computed Property"
}
}
}
// overriding the third property of Class A - allowed options --------------
class ClassB: ClassA {
override var computedPropertyWithGet: String {
get {
return "Overriding with Read-Only Computed Property"
}
}
}
class ClassC: ClassA {
override var computedPropertyWithGet: String {
get {
return "Overriding with Read-Write Computed Property"
}
set {
// some statements
}
}
}
// overriding the third property of Class A - not allowed options -----------
class ClassD: ClassA {
override var computedPropertyWithGet: String = "Overriding with Read-Write Stored Property"
}
class ClassE: ClassA {
override let computedPropertyWithGet: String = "Overriding with Read-Only Stored Property"
}
// overriding the fourth property of Class A - allowed options -------------
class ClassF: ClassA {
override var computedPropertyWithGetAndSet: String {
get {
return "Overriding with Read-Write Computed Property"
}
set {
// some statements
}
}
}
// overriding the fourth property of Class A - not allowed options ---------
class ClassG: ClassA {
override var computedPropertyWithGetAndSet: String {
get {
return "Overriding with Read-Only Computed Property"
}
}
}
class ClassH: ClassA {
override var computedPropertyWithGetAndSet: String = "Overriding with Read-Write Stored Property"
}