Swift中懶載入(lazy initialization)的實現

來源:互聯網
上載者:User

標籤:

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

Swift中懶載入(lazy initialization)的實現

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.