Source Code Analysis in Swift - @autoclosure

@autoclosure:字面理解意思就是自动闭包.

在Swift中有这样的运算符&&,我们知道&&运算符是阻断的

在Swift中运算符是一个函数,如果&&左边是false就不会计算右边的,直接返回false.

@inline(__always)
@warn_unused_result
public func && <T : Boolean, U : Boolean>(
  lhs: T, rhs: @autoclosure () throws -> U
) rethrows -> Bool {
  return lhs.boolValue ? try rhs().boolValue : false
}
@_transparent
@warn_unused_result
public func && <T : Boolean>(
  lhs: T, rhs: @autoclosure () throws -> Bool
) rethrows -> Bool {
  return lhs.boolValue ? try rhs().boolValue : false
}

从源码中我们可以看到,左参数为正常的Boolean,右参数并不是Boolean,而是用@autoclosure修饰的一个闭包.
(还是能抛出异常的)

为什么要这样呢?下面是函数前的提示,写的很完善,还给出例子,因为当第一个参数为false时就不需要计算第二个参数的.因为肯定是false.

/// Performs a logical AND operation on two Boolean values.
///
/// The `&&` (logical AND) operator combines two Boolean values and returns
/// `true` if both of the values are `true`. If either of the values is
/// `false`, the operator returns `false`.
///
/// This operator uses short-circuit evaluation: The left-hand side (`lhs`) is
/// evaluated first, and the right-hand side (`rhs`) is evaluated only if
/// `lhs` evaluates to `true`. For example:
///
///     let measurements = [7.44, 6.51, 4.74, 5.88, 6.27, 6.12, 7.76]
///     let sum = measurements.reduce(0, combine: +)
///
///     if measurements.count > 0 && sum / Double(measurements.count) < 6.5 {
///         print("Average measurement is less than 6.5")
///     }
///     // Prints "Average measurement is less than 6.5"
///
/// In this example, `lhs` tests whether `measurements.count` is greater than
/// zero. Evaluation of the `&&` operator is one of the following:
///
/// - When `measurements.count` is equal to zero, `lhs` evaluates to `false`
///   and `rhs` is not evaluated, preventing a divide-by-zero error in the
///   expression `sum / Double(measurements.count)`. The result of the
///   operation is `false`.
/// - When `measurements.count` is greater than zero, `lhs` evaluates to `true`
///   and `rhs` is evaluated. The result of evaluating `rhs` is the result of
///   the `&&` operation.

那为什么采用闭包的形式?

我们来举个栗子

模拟一下&&运算符:反映很快,很快就出结果

但是我们平常使用的时候并不是这么使用的.而是这样

然后你会发现等待大约五秒之后才显示结果,但是结果依旧是false

第一个参数已经是false了,第二个结果已经没有意义了,但是单纯的编译器会先调用a()这个函数计算返回结果的值,再进行判断.已经浪费了很多的时间和资源.

改进:采用闭包的形式:

结果很快就可以显示出来.因为闭包并没有立刻执行,而是等到第一个参数为true时才执行闭包.

但是你调用这个函数的时候使用{xxxx}的时候很不方便

再改进:采用@autoclosure修饰

这样是不是就很清晰.

@autoclosure只能用在()->T这样无参数的闭包中

时间: 2024-11-08 23:46:27

Source Code Analysis in Swift - @autoclosure的相关文章

Memcached source code analysis -- Analysis of change of state--reference

This article mainly introduces the process of Memcached, libevent structure of the main thread and worker thread based on the processing of the connection state of mutual conversion (not involving data access operations), the main business logic is t

Memcached source code analysis (threading model)--reference

Look under the start memcahced threading process memcached multi-threaded mainly by instantiating multiple libevent, are a main thread and n workers thread is the main thread or workers thread all through the the libevent management network event, in

CEPH CRUSH 算法源码分析 原文CEPH CRUSH algorithm source code analysis

原文地址 CEPH CRUSH algorithm source code analysis http://www.shalandis.com/original/2016/05/19/CEPH-CRUSH-algorithm-source-code-analysis/ 文章比较深入的写了CRUSH算法的原理和过程.通过调试深入的介绍了CRUSH计算的过程.文章中添加了些内容. 写在前面 读本文前,你需要对ceph的基本操作,pool和CRUSH map非常熟悉.并且较深入的读过源码. 分析的方法

AOP spring source code analysis

例子 1 在使用 New 的情况下实现 AOP public class TraceTest { public static void main(String args[]) { TraceTest test = new TraceTest(); test.rpcCall(); } // 虽然 intellij 没有给出提示,但是这个 Trace 还是成功的 @Trace public void rpcCall() { System.out.println("call rpc"); }

Golang Template source code analysis(Parse)

This blog was written at go 1.3.1 version. We know that we use template thought by followed way: func main() { name := "waynehu" tmpl := template.New("test") tmpl, err := tmpl.Parse("hello {{.}}") if err != nil { panic(err) }

Apache Commons Pool2 源码分析 | Apache Commons Pool2 Source Code Analysis

Apache Commons Pool实现了对象池的功能.定义了对象的生成.销毁.激活.钝化等操作及其状态转换,并提供几个默认的对象池实现.在讲述其实现原理前,先提一下其中有几个重要的对象: PooledObject(池对象). PooledObjectFactory(池对象工厂). Object Pool(对象池). 下面分别详细讲解它们的实现. PooledObject(池对象) 用于封装对象(如:线程.数据库连接.TCP连接),将其包裹成可被池管理的对象.提供了两个默认的池对象实现: De

Redis source code analysis

http://zhangtielei.com/posts/blog-redis-dict.html http://zhangtielei.com/assets/photos_redis/redis_dict_structure.png https://github.com/antirez/redis/blob/unstable/src/dict.c http://bbs.redis.cn/forum.php?mod=viewthread&tid=545 http://redisplanet.co

Top 40 Static Code Analysis Tools

https://www.softwaretestinghelp.com/tools/top-40-static-code-analysis-tools/ In this article, I have summarised some of the top static code analysis tools. Can we ever imagine sitting back and manually reading each line of codes to find flaws? To eas

[code] Transformer For Summarization Source Code Reading

Basic Information 作者:李丕绩(腾讯AI Lab) 模型:Transformer + copy mechanism for abstractive summarization 数据集:CNN/Daily Mail Parameters WARNING: IN DEBUGGING MODE USE COPY MECHANISM USE COVERAGE MECHANISM USE AVG NLL as LOSS USE LEARNABLE W2V EMBEDDING RNN TY