Written by Paul Hudson     @twostraws

It's very common in iOS to want to create complex objects only when you need them, largely because with limited computing power at your disposal you need to avoid doing expensive work unless it's really needed.

Swift has a mechanism built right into the language that enables just-in-time calculation of expensive work, and it is called a lazy variable. These variables are created using a function you specify only when that variable is first requested. If it's never requested, the function is never run, so it does help save processing time.

I don't want to produce a complicated example because that would rather defy the point, so instead I've built a simple (if silly!) one: imagine you want to calculate a person's age using the Fibonacci sequence. This sequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on – each number is calculated by adding the previous two numbers in the sequence. So if someone was aged 8, their Fibonacci sequence age would be 21, because that's at position 8 in the sequence.

I chose this because the most common pedagogical way to teach the Fibonacci sequence is using a function like this one:

That function calls itself, which makes it a recursive function, and actually it's quite slow. If you try to calculate the Fibonacci value of something over, say, 21, expect it to be slow in a playground!

Anyway, we want to create a Person struct that has an age property and a fibonacciAge property, but we don't want that second one to be evaluated unless it's actually used. So, create this struct now:

There are five important things to note in that code:

  • The lazy property is marked as lazy var. You can't make it lazy let because lazy properties must always be variables.
  • Because the actual value is created by evaluation, you need to declare its data type up front. In the case of the code above, that means declaring the property as Int.
  • Once you've set your data type, you need to use an open brace ("{") to start your block of code, then "}" to finish.
  • You need to use self inside the function. In fact, if you're using a class rather than a structure, you should also declare [unowned self] inside your function so that you don't create a strong reference cycle.
  • You need to end your lazy property with (), because what you're actually doing is making a call to the function you just created.

Once that code is written, you can use it like this:

Remember, the point of lazy properties is that they are computed only when they are first needed, after which their value is saved. This means if you create 1000 singers and never touch their fibonacciOfAgeproperty, your code will be lightning fast because that lazy work is never done.

Available from iOS 7.0

https://www.hackingwithswift.com/example-code/language/what-are-lazy-variables

What are lazy variables?的更多相关文章

  1. Beginning Scala study note(2) Basics of Scala

    1. Variables (1) Three ways to define variables: 1) val refers to define an immutable variable; scal ...

  2. Effective Java 71 Use lazy initialization judiciously

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

  3. lazy instructor

    Description A math instructor is too lazy to grade a question in the exam papers in which students a ...

  4. 数据结构——POJ 1686 Lazy Math Instructor 栈的应用

    Description A math instructor is too lazy to grade a question in the exam papers in which students a ...

  5. POJ 1686 Lazy Math Instructor (模似题+栈的运用) 各种坑

    Problem Description A math instructor is too lazy to grade a question in the exam papers in which st ...

  6. Lazy Math Instructor

      Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 3721   Accepted: 1290 Description A m ...

  7. Summary: Deep Copy vs. Shallow Copy vs. Lazy Copy

    Object copy An object copy is an action in computing where a data object has its attributes copied t ...

  8. Lazy的SDL教程 翻译----Lesson 22 Timing

    原文:http://lazyfoo.net/tutorials/SDL/22_timing/index.php Timing 计时 Last Updated 3/10/14 Another impor ...

  9. 代码的坏味道(15)——冗余类(Lazy Class)

    坏味道--冗余类(Lazy Class) 特征 理解和维护类总是费时费力的.如果一个类不值得你花费精力,它就应该被删除. 问题原因 也许一个类的初始设计是一个功能完全的类,然而随着代码的变迁,变得没什 ...

随机推荐

  1. 计蒜客 奇异家庭 (DP)

    链接 : Here! 思路 : 首先这棵家族树非常非常非常有特点, 家族里的人要么没有孩子, 要么有两个孩子, 所以这棵家族树是一颗满二叉树. 设定状态 $dp[i][j]$ 为 $i$ 个人组成的不 ...

  2. 【Codeforces 996B】World Cup

    [链接] 我是链接,点我呀:) [题意] [题解] 你可以找出来a[i]里面的最小值mi,显然是这个数字最可能先变成0,但还不确定. 然后用mi/n得到你最少需要走多少圈才能让那个mi变成" ...

  3. Windows 安装react native

    1.下载node.js (https://nodejs.org/en/) 2.安装node.js,安装完成后按住 图标键+R ,输入CMD进入命令行终端,输入npm -v C:\Users\Admin ...

  4. 洛谷 P1640 BZOJ 1854 [SCOI2010]连续攻击游戏

    题目描述 lxhgww最近迷上了一款游戏,在游戏里,他拥有很多的装备,每种装备都有2个属性,这些属性的值用[1,10000]之间的数表示.当他使用某种装备时,他只能使用该装备的某一个属性.并且每种装备 ...

  5. mysql 多个select需要放入一个事务吗?

    第一次写博客,还请大家多多支持 今天同事问了个问题:在多个select的时候,用不用放入同一个事务? 首先先看个例子: public class JDBCClient { public static  ...

  6. 0929MySQL JOIN的算法

    http://www.cnblogs.com/starhu/p/6418842.html http://www.cnblogs.com/starhu/p/6418833.html http://www ...

  7. 0926MySQL中ICP索引下推

    转自 http://blog.itpub.net/22664653/viewspace-1678779/ [MySQL]MySQL5.6新特性之Index Condition Pushdown2015 ...

  8. Xcode6+Cocos2d-x真机调试 报错

    眼下真机调试时遇到下面问题. Undefined symbols for architecture arm64: "_png_get_io_ptr", referenced fro ...

  9. Leetcode45:Intersection of Two Linked Lists

    Write a program to find the node at which the intersection of two singly linked lists begins. For ex ...

  10. iOS 获取当前时间格式化字符串

    iOS 获取当前时间格式化字符串 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保 ...