Page 47
infix operator ?? { associativity right precedence 110 }
func ??<T>(optional: T?, defaultValue: T) -> T {
if let x = optional {
return x
} else {
return defaultValue
}
}
上面实现了操作符 ?? 但书中指出存在一个问题:
There is one problem with this definition: the defaultValue may be evaluated, regardless of whether or not the optional is nil. This is usually undesirable behavior: an if-then-else statement should only execute one of its branches, depending on whether or not the associated condition is true. Similarly, the ?? operator should only evaluate the defaultValue argument when the optional argument is nil. As an illustration, suppose we were to call ??, as follows:
optional ?? defaultValue
In this example, we really do not want to evaluate defaultValue if the optional variable is non-nil — it could be a very expensive computation that we only want to run if it is absolutely necessary.
最后swift库中正确的实现是这样的:
func ??<T>(optional: T?, defaultValue: @autoclosure () -> T) -> T {
if let x = optional {
return x
} else {
return defaultValue()
}
}
请问 the defaultValue may be evaluated, regardless of whether or not the optional is nil 为什么会存在这个问题呢
1
eternityz 2015-02-07 19:11:53 +08:00 1
不使用 @autoclosure 时 func ?? 的两个参数会在传入时求值. 使用 @autoclosure 就把求值过程延后到了调用 defaultValue() 的时候. 就是所谓的 lazy evaluation. 官方 blog 有介绍: https://developer.apple.com/swift/blog/?id=4
|
2
walkingway OP @eternityz 多谢,明白了
|