这是我要翻译成 Swift 的 Objective-C 代码:
@implementation Audio
@synthesize fileCode = _fileCode;
- (NSString *)fileCode
{
if (!_fileCode)
_fileCode = [[NSUUID UUID] UUIDString];
return _fileCode;
}
...
这里是翻译的开始:
class Audio: NSObject {
var fileID: Int?
lazy var fileCode = {
return NSUUID.UUID().UUIDString;
}
...
假设 UUID 计算不必要地昂贵,我想在必要时避免它。
在 Objective-C 中的用例:
Audio bob = [[Audio alloc] init];
bob.fileCode = "CODE";
不会导致惰性初始化器被调用,因为 getter 会跳过它。
对于 Swift,我能保证这一点吗?
最佳答案
这正是lazy
的定义,来自the docs :
A lazy stored property is a property whose initial value is not calculated until the first time it is used.
关于swift - 在 Swift 中,如果编写了 var,是否调用了一个惰性实例化器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34344831/