2016-09-20 21 views

回答

2

是一个结构可以有一个懒惰的财产。考虑下面这个例子:

class Stuff { 
    var stuff: Int 

    init(value: Int) { 
     print("Stuff created with value \(value)") 
     stuff = value 
    } 
} 

struct HasLazy { 
    lazy var object = Stuff(value: 1) 
    var object2 = Stuff(value: 2) 
} 

func testIt() { 
    print("in testIt") 

    var haslazy = HasLazy() 

    print("done") 
    haslazy.object.stuff = 17 
    print("\(haslazy.object.stuff)") 
    print("final") 
} 

testIt() 

输出:

in testIt 
Stuff created with value 2 
done 
Stuff created with value 1 
17 
final 

注意,属性标记lazy未初始化后才"done"打印时第一次访问属性。

看到它在行动here,然后尝试没有lazy关键字。

+0

好完美就是我正在寻找。谢谢! – FTNomad

相关问题