gpt4 book ai didi

swift - 如何更改子类中的 Swift 属性可见性

转载 作者:搜寻专家 更新时间:2023-11-01 06:07:06 26 4
gpt4 key购买 nike

有没有办法在不引入新属性的情况下更改子类中的 Swift 属性可见性?

我想做的是(将属性初始化为默认值不是强制要求):

public class MyBaseClass
{
private var abc: Int = 0
}

public class MyClass: MyBaseClass
{
public override var abc: Int = 0 // this cannot be compiled
}

以上代码显示编译器错误:

Cannot override with stored property 'abc'

目前我能解决这个问题的唯一方法是引入另一个属性,但这不是我喜欢做的:

public class MyClass: MyBaseClass
{
public var abcd: Int
{
get
{
return abc
}

set
{
abc = newValue
}

}
}

最佳答案

Swift 有两种类型的属性:存储属性和计算属性。您可以同时覆盖它们,但覆盖的版本不能是存储属性,您必须使用计算属性进行覆盖。

请注意,存储属性只是一 block 内存,而计算属性是一组两个方法 - getter 和 setter。您不能用另一 block 内存覆盖一 block 内存,但可以覆盖一个方法。

参见 Inheritance - Overriding ,部分 覆盖属性

You can override an inherited instance or type property to provide your own custom getter and setter for that property, or to add property observers to enable the overriding property to observe when the underlying property value changes.

You can provide a custom getter (and setter, if appropriate) to override any inherited property, regardless of whether the inherited property is implemented as a stored or computed property at source. The stored or computed nature of an inherited property is not known by a subclass—it only knows that the inherited property has a certain name and type. You must always state both the name and the type of the property you are overriding, to enable the compiler to check that your override matches a superclass property with the same name and type.

You can present an inherited read-only property as a read-write property by providing both a getter and a setter in your subclass property override. You cannot, however, present an inherited read-write property as a read-only property.

还有一个注释:

If you provide a setter as part of a property override, you must also provide a getter for that override. If you don’t want to modify the inherited property’s value within the overriding getter, you can simply pass through the inherited value by returning super.someProperty from the getter, where someProperty is the name of the property you are overriding.

它确切地告诉我们该做什么:

public class MyClass: MyBaseClass {
public override var abc: Int {
get {
return super.abc
}
set {
super.abc = newValue
}
}
}

请注意,以下内容也适用。我们只需要确保我们有一个计算属性:

public class MyClass: MyBaseClass {
public override var abc: Int {
didSet {
}
}
}

关于swift - 如何更改子类中的 Swift 属性可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34786237/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com