What are lazy variables?
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 itlazy letbecause 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
selfinside 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?的更多相关文章
- 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 ...
- Effective Java 71 Use lazy initialization judiciously
Lazy initialization - It decreases the cost of initializing a class or creating an instance, at the ...
- lazy instructor
Description A math instructor is too lazy to grade a question in the exam papers in which students a ...
- 数据结构——POJ 1686 Lazy Math Instructor 栈的应用
Description A math instructor is too lazy to grade a question in the exam papers in which students a ...
- POJ 1686 Lazy Math Instructor (模似题+栈的运用) 各种坑
Problem Description A math instructor is too lazy to grade a question in the exam papers in which st ...
- Lazy Math Instructor
Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 3721 Accepted: 1290 Description A m ...
- 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 ...
- Lazy的SDL教程 翻译----Lesson 22 Timing
原文:http://lazyfoo.net/tutorials/SDL/22_timing/index.php Timing 计时 Last Updated 3/10/14 Another impor ...
- 代码的坏味道(15)——冗余类(Lazy Class)
坏味道--冗余类(Lazy Class) 特征 理解和维护类总是费时费力的.如果一个类不值得你花费精力,它就应该被删除. 问题原因 也许一个类的初始设计是一个功能完全的类,然而随着代码的变迁,变得没什 ...
随机推荐
- 优秀的web端 vue框架
之前得到消息vue在GitHub已经超过react,成为第一大框架,让我们来看看以vue为基础的开发框架有哪些? Element(start-28128) 饿了么前端推出的基于 Vue.js 2.0 ...
- eslint 校验去除
不允许对 function 的参数进行重新赋值 /* eslint no-param-reassign: ["error", { "props": false ...
- 51nod1242斐波那契数列的第N项 【矩阵快速幂】
斐波那契数列的定义如下: F(0) = 0 F(1) = 1 F(n) = F(n - 1) + F(n - 2) (n >= 2) (1, 1, 2, 3, 5, 8, 13, 21, 34, ...
- 使用正则表达式爬取500px上的图片
网址:https://500px.com/seanarcher,seanarcher是一个up主的名字 打开这个网址,会发现有好多图片,具体到每一个图片的url地址 https://500px.com ...
- CentOS安装新版RabbitMQ解决Erlang 19.3版本依赖
通过yum等软件仓库都可以直接安装RabbitMQ,但版本一般都较为保守. RabbitMQ官网提供了新版的rpm包(http://www.rabbitmq.com/download.html),但是 ...
- 【1】Django概述
道生一,一生二,二生三,三生万物 无名天地之始,有名万物之母 ——老子 python程序web项目开发,是非常重要的一部分,Python为基础的web项目开发的框架有很多,django无疑是最强大we ...
- Bootstrap关于表格
1.Bootstrap为表格提供了1种基础样式和4种附加样式以及1个支持响应式的表格. ☑ .table:基础表格 ☑ .table-striped:斑马线表格 ☑ .table-bordere ...
- Linux查看 kennel , 物理CPU个数、核数、逻辑CPU个数
other article on my list: 查看进程 https://i.cnblogs.com/PostDone.aspx?postid=9231604&actiontip=%E4% ...
- 洛谷 P1768 天路
P1768 天路 题目描述 “那是一条神奇的天路诶~,把第一个神犇送上天堂~”,XDM先生唱着这首“亲切”的歌曲,一道猥琐题目的灵感在脑中出现了. 和C_SUNSHINE大神商量后,这道猥琐的题目终于 ...
- VMware 12安装CentOS 6.9时出现:The centos disc was not found in any of your drives.Please insert the centos disc and press OK to retry
错误: The centos disc was not found in any of your drives.Please insert the centos disc and press OK t ...