swift - 在 Swift 中,如果编写了 var,是否调用了一个惰性实例化器?

标签 swift

这是我要翻译成 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/

相关文章:

swift - 在父类(super class)中实现 CodingKey 映射

swift - 无法快速访问在 UITableviewcontroller 函数外声明的变量

iphone - 从用作 tableHeaderView 的 xib 文件内的按钮转到 VC

iphone - 如何在 Swift 中声明自定义类对象的数组

ios - UICollectionViewCell 大小根据 Screen/FrameSize Swift

objective-c - 如何将 UIImage 从 iPhone 应用程序传递到 Apple Watch 应用程序

ios - 点击手势以使用 TableView 关闭 UITextField

ios - 使用 let buttonPosition = sender.convertPoint(CGPointZero, toView : self. tableView) 点击时更改 TableViewCell 中 UIButton 的标题

xcode - UISearchController 不更新

ios - 使用 Storyboard 时实例化 ViewController