V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
iOS 开发实用技术导航
NSHipster 中文版
http://nshipster.cn/
cocos2d 开源 2D 游戏引擎
http://www.cocos2d-iphone.org/
CocoaPods
http://cocoapods.org/
Google Analytics for Mobile 统计解决方案
http://code.google.com/mobile/analytics/
WWDC
https://developer.apple.com/wwdc/
Design Guides and Resources
https://developer.apple.com/design/
Transcripts of WWDC sessions
http://asciiwwdc.com
Cocoa with Love
http://cocoawithlove.com/
Cocoa Dev Central
http://cocoadevcentral.com/
NSHipster
http://nshipster.com/
Style Guides
Google Objective-C Style Guide
NYTimes Objective-C Style Guide
Useful Tools and Services
Charles Web Debugging Proxy
Smore
walkingway
V2EX  ›  iDev

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

  •  
  •   walkingway · 2015-02-07 18:31:02 +08:00 · 3449 次点击
    这是一个创建于 3579 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    2 条回复    2015-02-07 19:47:44 +08:00
    eternityz
        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
    walkingway
        2
    walkingway  
    OP
       2015-02-07 19:47:44 +08:00
    @eternityz 多谢,明白了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5949 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 02:03 · PVG 10:03 · LAX 18:03 · JFK 21:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.