objc.io 那本《Functional Programming in swift》书中的一个疑问

2015-02-07 18:31:02 +08:00
 walkingway

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 为什么会存在这个问题呢

3390 次点击
所在节点    iDev
2 条回复
eternityz
2015-02-07 19:11:53 +08:00
不使用 @autoclosure 时 func ?? 的两个参数会在传入时求值. 使用 @autoclosure 就把求值过程延后到了调用 defaultValue() 的时候. 就是所谓的 lazy evaluation. 官方 blog 有介绍: https://developer.apple.com/swift/blog/?id=4
walkingway
2015-02-07 19:47:44 +08:00
@eternityz 多谢,明白了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/169089

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX