阅读后@property/@synthesize equivalent in swift,我对如何保留Objective C的功能感到好奇。有没有办法在Swift中重写“属性”设置器和获取器?
说我有在目标C以下:
@interface MyClass
@property (readwrite) MyType *myVar;
@end
这可以像这样的访问与点状和Smalltalk-基于语法:
Type *newVar1 = myClassInstance.myVar;
Type *newVar2 = [myClassInstance myVar];
myClassInstance.myVar = newVar1;
[myClassInstance setMyVar: newVar2];
如果我想添加一些额外的我可以这样做:
@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说,斯威夫特没有属性和实例变量之间进行区分。所以,说我在斯威夫特如下:
class MyClass {
var myVar: MyType
}
就我所知,访问myVar
唯一的方法是这样的:
var newVar1 = myClassInstance.myVar;
myClassInstance.myVar = newVar1;
但我不知道如何定制这些获得者和制定者。 是否有与Objective C @property
重叠的Swift等价物?
说到'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' – 2015-04-01 17:43:46
@AirspeedVelocity谢谢! – 2015-04-01 18:09:45