码迷,mamicode.com
首页 > 编程语言 > 详细

Source Code Analysis in Swift - @autoclosure

时间:2016-05-11 15:11:26      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

@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这样无参数的闭包中

Source Code Analysis in Swift - @autoclosure

标签:

原文地址:http://www.cnblogs.com/xwjack1554239786/p/5481706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!