Lazy initialization (also sometimes called lazy instantiation, or lazy loading) is a technique for delaying the creation of an object or some other expensive process until it’s needed. When programming for iOS, this is helpful to make sure you utilize only the memory you need when you need it.

This technique is so helpful, in fact, that Swift added direct support for it with the lazyattribute.

To understand why this is useful, let’s first go over the old way of creating lazy properties.


The Old Way

In Objective-C, if you had a mutable array property you wanted lazily initialized, you’d have to write this:

@property (nonatomic, strong) NSMutableArray *players;

- (NSMutableArray *)players {
if (!_players) {
_players = [[NSMutableArray alloc] init];
}
return _players;
}

To people new to Objective-C, this presents a few different learning curves. First of all, you need to know that the method name has to exactly match the property name. If you misspelled the method name, this would silently fail and players would be nil when you tried to access it.

You also need to know the _players instance variable was created for you automatically when your property was synthesized. Before Xcode 4.4, you had to manually synthesize your variable using the @synthesize keyword, like so:

@synthesize players;
// - or -
@synthesize players = _players;

Which would tell you that the instance variable used for the players property is _players. Nowadays Xcode handles synthesizing your properties for you. If you didn’t know that, then using the underscore before the property name might not be immediately obvious.


The Swift Way

Now in Swift, this can all be simplified down to one line:

lazy var players = [String]()

Simple, concise, and straight to the point.

Keep in mind you do need to declare your lazy property using the var keyword, not the letkeyword, because constants must always have a value before initialization completes.

If you wanted to add logic to your lazy initialization, Swift makes this easy by letting you define a closure after your lazy property:

lazy var players: [String] = {
var temporaryPlayers = [String]()
temporaryPlayers.append("John Doe")
return temporaryPlayers
}()

If you prefer, you can also lazily initiate your property using an instance method:

lazy var players: [String] = self.initialPlayers()

func initialPlayers() -> [String] {
var players = ["John Doe"]
return players
}

Or a class method:

class TestClass {
lazy var players = TestClass.initialPlayers() class func initialPlayers() -> [String] {
var players = ["John Doe"]
return players
} }

But people will most likely prefer using the new closure mechanic, as it keeps the logic near the property declaration.


When should I use lazy initialization?

One example of when to use lazy initialization is when the initial value for a property is not known until after the object is initialized.

For example, if you have a Person class and a personalizedGreeting property. The personalizedGreeting property can be lazily instantiated after the object is created so it can contain the name of the person. Here’s a quick example:

class Person {

    var name: String

    lazy var personalizedGreeting: String = {
[unowned self] in
return "Hello, \(self.name)!"
}() init(name: String) {
self.name = name
}
}

(Note that we had to say [unowned self] in here to prevent a strong reference cycle)

When you initialize a person, their personal greeting hasn’t been created yet:

let person = Person(name: "John Doe")
// person.personalizedGreeting is nil

But when you attempt to print out the personalized greeting, it’s calculated on-the-fly:

NSLog(person.personalizedGreeting)
// personalizedGreeting is calculated when used
// and now contains the value "Hello, John Doe!"

Another good time to use lazy initialization is when the initial value for a property is computationally intensive.

For example, if you have an object that performs some really intense algorithm to determine the number of faces in a picture, make the numberOfFaces property lazily initialized.

Or if you had a class that calculates several different large numbers, you would want to make sure they’re only calculated on-demand:

class MathHelper {

    lazy var pi: Double = {
// Calculate pi to a crazy number of digits
return resultOfCalculation
}() }

Conclusion

Direct support for lazy property initialization is just one of the many great features of Swift. In the next few months, I’ll cover more great features and shortcuts. Stay tuned!

Updated 7/23/14: Updated to reflect the @lazy attribute being changed to lazy. Also updated to the new Array declaration syntax.

http://mikebuss.com/2014/06/22/lazy-initialization-swift/

Lazy Initialization with Swift的更多相关文章

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

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

  2. 单例模式的两种实现方式对比:DCL (double check idiom)双重检查 和 lazy initialization holder class(静态内部类)

    首先这两种方式都是延迟初始化机制,就是当要用到的时候再去初始化. 但是Effective Java书中说过:除非绝对必要,否则就不要这么做. 1. DCL (double checked lockin ...

  3. Effective Java 71 Use lazy initialization judiciously

    Lazy initialization - It decreases the cost of initializing a class or creating an instance, at the ...

  4. Swift - 懒加载(lazy initialization)

    Swift中是存在和OC一样的懒加载机制的,在程序设计中,我们经常会使用 懒加载 ,顾名思义,就是用到的时候再开辟空间 懒加载 格式: lazy var 变量: 类型 = { 创建变量代码 }() 懒 ...

  5. Double-check idiom for lazy initialization of instance fields

  6. 单例模式-Lazy initialization holder class模式

    这个模式综合使用了Java的类级内部类和多线程缺省同步锁的知识,很巧妙地同时实现了延迟加载和线程安全. 1.相应的基础知识 什么是类级内部类? 简单点说,类级内部类指的是,有static修饰的成员式内 ...

  7. Swift 实现单例模式Singleton pattern的三种方法

    转自:点击打开链接 From my short experience with Swift there are three approaches to implement the Singleton ...

  8. Awesome Swift

    Awesome Swift https://github.com/matteocrippa/awesome-swift A collaborative list of awesome Swift re ...

  9. [你必须知道的.NET]第三十三回,深入.NET 4.0之,Lazy<T>点滴

    发布日期:2009.10.29 作者:Anytao © 2009 Anytao.com ,Anytao原创作品,转贴请注明作者和出处. 对象的创建方式,始终代表了软件工业的生产力方向,代表了先进软件技 ...

随机推荐

  1. SpringBoot快速创建HelloWorld项目

    废话不多提,拿起键盘,打开 IDEA 就是一通骚操作. 打开 IDEA 后,首页选择 Create New Project,再接着按下图所示,快速搭建SpringBoot项目. 接下来将 Group ...

  2. 34.初识搜索引擎及timeout机制

    主要知识点 1.对搜索执行结果的说明 2.timeout机制讲解 一.对执行 GET /_search 的结果的说明 执行结果如下(只保留部分) { "took": 29, &qu ...

  3. Golang - 流程控制

    目录 Golang - 流程控制 1. 选择结构 2. 循环结构 3. 跳转语句 Golang - 流程控制 1. 选择结构 if else语句: //package 声明开头表示代码所属包 pack ...

  4. 使用Layer完成图片放大功能

    序言:在写这个功能之前也用了zoom.js,zoom.js用起来简单引用js然后设置图片属性就可以放大.但是放大后的图片模糊.没有遮罩.在放大图片时其它图片布局会受到影响,当然如果觉得这些都是小问题的 ...

  5. [bzoj3209]花神的数论题_数位dp

    花神的数论题 bzoj-3209 题目大意:sum(i)表示i的二进制表示中1的个数,求$\prod\limits_{i=1}^n sum(i)$ 注释:$1\le n\le 10^{15}$. 想法 ...

  6. [WordPress]基本操作

    编辑文本 文本模式下 more 提取摘要<!--more-->

  7. 关于DM8168中移植算法速度慢、效率低的新发现

    有不少的朋友,特别是刚刚接触DSP的朋友.基于DVRRDK编写C代码发现执行速度特别慢,我在上面简单的对每一个像素的UV分量赋值=0x80,这样就成了灰度图像.对1080P图像进行操作,发现处理每帧要 ...

  8. python中获取当前路径【os模块】

    本机windows,文件目录F:\python\ClStudyDemo\osTest.py os.path.realpath(_file_)——返回真实路径 os.path.split()——返回路径 ...

  9. Myeclipse快捷键备忘

    1.编辑类 Ctrl+定义好的类名     链接到你定义好的类的窗口 Ctrl + /               为选中的一段代码加上或去掉注释符   //       (必须选中代码块) Ctrl ...

  10. UVa 572 - Oil Deposits (简单dfs)

    Description GeoSurvComp地质调查公司负责探測地下石油储藏. GeoSurvComp如今在一块矩形区域探測石油.并把这个大区域分成了非常多小块.他们通过专业设备.来分析每一个小块中 ...