【问题标题】:Can subclass inherit type property from its super class? And if yes, how to override it?子类可以从其超类继承类型属性吗?如果是,如何覆盖它?
【发布时间】:2017-01-07 19:26:58
【问题描述】:

code running in xcode

“对于类类型的计算类型属性,您可以使用 class 关键字来允许子类覆盖超类的实现。”

“您可以覆盖继承的实例或类型属性,为该属性提供您自己的自定义 getter 和 setter” ----苹果Swift3

//override static
class A{
    var myValue = 0614
    static var storedTypeProperty = "Some value"
    class var overrideableComputedTypeProperty: Int {
        return 1
    }
}
class B: A {
    storedTypeProperty = "New String"
}

B 似乎没有从 A 继承任何类型属性。 那么如何覆盖上面 Swift3 书中描述的“继承类型属性”。

【问题讨论】:

  • 你想达到什么目的?您不能覆盖 static 属性,但您可以使用其他变量来执行此操作。
  • 我不明白 Swift3 中提到的这两句话是什么意思。它说你可以重写一个继承的类型属性来为这个属性提供你自己的自定义 getter 和 setter。

标签: ios inheritance properties swift3 overriding


【解决方案1】:

您面临的问题是因为您使用的是static 变量。 static变量不能被覆盖,句号。没有必要在这里争论。

第一句话说,如果你有一个class(不是struct),比如class A {},你可以使用class关键字代替static关键字,并覆盖类类型。这意味着,您可以将两个关键字用于同一目的,但主要区别在于,static 不能被覆盖。

class A {
    // overridable computed property
    class var overridableClassPropery: String {
        return "This is class A's overwritten property" 
    }

    // Not overridable `static` computed property
    // Error will be shown if you try to override this property in class `B`
    static var notOverridableStaticPropery: String {
        return "Can not override this property in a subclass"
    }
}

第二个说,您可以覆盖超类的类属性,并在子类中提供您自己的get 实现,如下所示:

  class B: A {
    // Class type computed property can be overwritten
    override class var overridableClassPropery: String {
        return "This is class B's overwritten property"
    }
}

编辑:

class AnotOverridableStaticProperyclass B继承了,什么意思,可以通过class B访问/调用。 但是您不能覆盖它,它的值将始终设置在class A 中。

print(A.notOverridableStaticPropery) // prints "This is class A's not overridable static property"
print(B.notOverridableStaticPropery) // prints "This is class A's not overridable static property" 

【讨论】:

  • 好吧,还有一点我不明白,第二句中提到了“继承类型属性”,所以,B应该从A继承类型属性“notOverridableStaticProperty”,但是我可以'不要在 B 上调用此类型属性,我错过了什么?
猜你喜欢
  • 2022-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
  • 1970-01-01
  • 2014-11-21
  • 1970-01-01
  • 2012-11-01
相关资源
最近更新 更多