【问题标题】:Is there a way to override "property" setters and getters in Swift?有没有办法覆盖 Swift 中的“属性”设置器和获取器?
【发布时间】:2015-04-01 16:23:23
【问题描述】:

阅读@property/@synthesize equivalent in swift后,我开始好奇Objective C的功能是如何保留的。

假设我在 Objective C 中有以下内容:

@interface MyClass
@property (readwrite) MyType *myVar;
@end

这可以通过基于点和 smalltalk 的语法来访问:

Type *newVar1 = myClassInstance.myVar;
Type *newVar2 = [myClassInstance myVar];

myClassInstance.myVar = newVar1;
[myClassInstance setMyVar: newVar2];

如果我想为这些 getter/setter 添加一些额外的功能,我可以这样做:

@implementation MyClass

- (MyType *) myVar
{
    // do more stuff
    return self._myVar;
}

- (void) setMyVar: (MyType *) newVar
{
    self._myVar = newVar;
    // do more stuff
}

@end

(另见Custom setter for @property?

然而,the accepted answer to the above linked question 表示 Swift 不区分属性和实例变量。所以,假设我在 Swift 中有以下内容:

class MyClass {
    var myVar: MyType
}

据我所知,访问myVar 的唯一方法是:

var newVar1 = myClassInstance.myVar;

myClassInstance.myVar = newVar1;

但我不知道如何自定义这些 getter 和 setter。 是否有 Swift 等效的 Objective C @property 覆盖?

【问题讨论】:

    标签: swift properties objective-c-swift-bridge


    【解决方案1】:

    在研究这个问题时,我实际上偶然发现了我的答案,但仍然认为应该将它放在这里以供其他有相同问题的人使用。


    是的,根据the Swift Programming Language documentation's page on Properties,getter 和 setter 的制作方式与 C# 解决问题的方式类似:

    struct MyParentType {
        var myPlainVar: MyType = MyType()
        
        var myCustomGetterVar: MyType {
            // do more stuff
            return self.myCustomGetterVar
        }
        
        var myCustomGetterSetterVar: MyType {
            get {
                // do more stuff
                return self.myCustomGetterSetterVar
            }
            set {
                // do stuff
                self.myCustomGetterSetterVar = newValue
                // do more stuff
            }
        }
        
        var myCustomFancyVar: MyType? {
            willSet {
                // do stuff with newValue
            }
            // actual setting is done automatically, so no set{}
            didSet {
                // do more stuff with oldValue
            }
        }
    }
    

    请注意,带有didSet 的变量必须是初始化的或可选的,并且不能有get,因为使用get 计算的属性可以很容易地实现它们自己的didSetwillSet,如果他们愿意的话。

    【讨论】:

    • 说到willSet/didSet,你有点搞混了。您使用的 ! 不是解包运算符 - 您将 myCustomFancyVar 声明为“隐式解包可选”,即可以具有 nil 值的变量。由于这些不必初始化(它们默认为nil),因此您不必给它一个默认值。但是如果你给它一个初始值或使用一个初始化器,你就不需要!struct S { var x: Int = 1 { willSet(newVal) { println("willSet: \(newVal)") } didSet { println("did set") } } }; var s = S(x: 5); s.x = 2
    • @AirspeedVelocity 谢谢!
    猜你喜欢
    • 2014-03-11
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 2011-06-02
    相关资源
    最近更新 更多