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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM