Swift中懒加载(lazy initialization)的实现

Swift中是存在和OC一样的懒加载机制的,但是这方面国内的资料比较少,今天把搜索引擎换成了Bing后发现用Bing查英文\最新资料要比百度强上不少。

我们在OC中一般是这样实现懒加载初始化的:

   1:  @property (nonatomic, strong) NSMutableArray *players;
   2:   
   3:  - (NSMutableArray *)players {
   4:      if (!_players) {
   5:          _players = [[NSMutableArray alloc] init];
   6:      }
   7:      return _players;
   8:  }

 

而用百度搜“swift 懒加载 lazy”却没有像样的资料,都在照本宣科。

 

实际上我们可以这样写:

   1:  lazy var players: NSMutableArray = {
   2:          var temporaryPlayers = NSMutableArray()
   3:          temporaryPlayers.addObject("Mike Buss")
   4:          return temporaryPlayers
   5:          }()

 

完美解决问题!感谢Bing!

 

Lazy Initialization with Swift

http://www.tuicool.com/articles/I3mY7v

 

http://stackoverflow.com/questions/24068829/lazy-loading-properties-in-swift

posted @ 2015-05-08 07:57  有奈了  阅读(3221)  评论(0编辑  收藏  举报