V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
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 · Feb 7, 2015 · 3813 views
    This topic created in 4109 days ago, the information mentioned may be changed or developed.

    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 replies    2015-02-07 19:47:44 +08:00
    eternityz
        1
    eternityz  
       Feb 7, 2015   ❤️ 1
    不使用 @autoclosure 时 func ?? 的两个参数会在传入时求值. 使用 @autoclosure 就把求值过程延后到了调用 defaultValue() 的时候. 就是所谓的 lazy evaluation. 官方 blog 有介绍: https://developer.apple.com/swift/blog/?id=4
    walkingway
        2
    walkingway  
    OP
       Feb 7, 2015
    @eternityz 多谢,明白了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3461 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 10:41 · PVG 18:41 · LAX 03:41 · JFK 06:41
    ♥ Do have faith in what you're doing.