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

时间:2021-03-17 16:11:52

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:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

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

 

实际上我们可以这样写:

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

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

完美解决问题!感谢Bing!

 

Lazy Initialization with Swift

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

 

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