【发布时间】: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