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. Modbus串行通信

    一.Modbus通信协议简介 1. Modbus协议 Modbus 是一个请求/应答协议,并且提供功能码规定的服务.Modbu协议是 OSI 模型第 7 层上的应用层报文传输协议. MODBUS协议支 ...

  2. OBS直播和相关操作

    OBS Studio(Open Broadcaster Software)是一个免费的开源的视频录制和视频实时流软件.其有多种功能并广泛使用在视频采集,直播等领域. https://obsprojec ...

  3. 去除html标签 php

    function my_html($string,$sublen =80){ $string = strip_tags($string); $string = preg_replace ('/\n/i ...

  4. ExtJs之Ajax模式的表单数据加载

    简单: <!DOCTYPE html> <html> <head> <title>ExtJs</title> <meta http-e ...

  5. 【函数式】Monads模式初探——Endofunctor

    自函子 自函子(Endofunctor)是一个将范畴映射到自身的函子(A functor that maps a category to itself). 函子是将一个范畴转换到另一个范畴.所以自函子 ...

  6. Lightoj 1112 - Curious Robin Hood 【单点改动 + 单点、 区间查询】【树状数组 水题】

    1112 - Curious Robin Hood PDF (English) Statistics Forum Time Limit: 1 second(s) Memory Limit: 64 MB ...

  7. SecureCRT图形界面(通过设置调用Xmanager - Passive程序)

    首先,在server进行设置 假设server是图形化界面启动的,xhost +命令能够不用运行 [root@test ~]# xhost + xhost:  unable to open displ ...

  8. 什么是A记录、MX记录、CNAME记录具体介绍

    什么是A记录: A (Address) 记录是用来指定主机名(或域名)相应的IP地址记录.用户能够将该域名下的站点服务器指向到自己的web server上. 同一时候也能够设置域名的子域名. 通俗来说 ...

  9. ios weak和strong的差别

    The difference is that an object will be deallocated as soon as there are no strong pointers to it. ...

  10. linux中udev简单的用法-->【转】

    本文转载自:http://blog.csdn.net/qq_29729577/article/details/50825134 udev是Linux提供的一种在用户态管理设备的一种机制,udev的详细 ...