Swift optional chaining doesn't work in closure

后端 未结 4 1873
孤独总比滥情好
孤独总比滥情好 2020-12-03 13:45

My code looks like this. My class has an optional var

var currentBottle : BottleLayer?

BottleLayer has a method jiggle().

相关标签:
4条回答
  • 2020-12-03 14:10
    let closure = { () -> () in
        self.currentBottle?.jiggle()
        return
    }
    

    Otherwise the compiler thinks the result of that statement should be returned from the closure and it realizes there is a mismatch between () (return type) and the optional returned by the statement (Optional<Void>). By adding an explicit return, the compiler will know that we don't want to return anything.

    The error message is wrong, of course.

    0 讨论(0)
  • 2020-12-03 14:16

    This is NOT a bug. It's simply your closure type which is wrong. The correct type should return an optional Void to reflect the optional chaining:

    let clos = { ()->()? in currentBottle?.jiggle() }
    

    The problem in details:

    • You declare your closure as a closure that returns Void (namely ->()).
    • But, do remember that, as like every time you use optional chaining, the return type of the whole expression is of optional type. Because your closure can either return Void if currentBottle do exists… or nil if it doesn't!

    So the correct syntax is to make your closure return a Void? (or ()?) instead of a simple Void

    class BottleLayer {
        func jiggle() { println("Jiggle Jiggle") }
    }
    var currentBottle: BottleLayer?
    currentBottle?.jiggle() // OK
    let clos = { Void->Void? in currentBottle?.jiggle() } // Also OK
    let clos = { () -> ()? in currentBottle?.jiggle() } // Still OK (Void and () are synonyms)
    

    Note: if you had let Swift infer the correct type for you instead of explicitly forcing it, it would have fixed the issue for you:

    // Even better: type automatically inferred as ()->()? — also known as Void->Void?
    let clos = { currentBottle?.jiggle() }
    

    [EDIT]

    Additional trick: directly assign the optional chaining to a variable

    You can even assign the function directly to a variable, like so:

    let clos2 = currentBottle?.jiggle // no parenthesis, we don't want to call the function, just refer to it
    

    Note that the type of clos2 (which is not explicitly specified here and is thus inferred automatically by Swift) in this case is not Void->Void? — namely a function that returns either nil or Void) as in the previous case — but is (Void->Void)?, which is the type for "an optional function of type Void->Void".

    This means that clos2 itself is "either nil or is a function returning Void". To use it, you could once again use optional chaining, simply like that:

    clos2?()
    

    This will evaluate to nil and do nothing if clos2 is itself nil (likely because currentBottle is itself nil)… and execute the closure — thus the currentBottle!.jiggle() code — and return Void if clos2 is non-nil (likely because currentBottle itself is non-nil).

    The return type of clos2?() itself is indeed Void?, as it returns either nil or Void.

    Doing the distinction between Void and Void? may seem pointless (after all, the jiggle function does not return anything in either case), but it let you do powerful stuff like testing the Void? in an if statement to check if the call actually did happen (and returned Void namely nothing) or didn't happen (and return nil):

    if clos2?() { println("The jiggle function got called after all!") }
    

    [EDIT2] As you (@matt) pointed out yourself, this other alternative has one other major difference: it evaluates currentBottle?.jiggle at the time that expression got affected to clos2. So if currentBottle is nil at that time, clos2 will be nil… even if currentBottle got a non-nil value later.

    Conversely, clos is affected to the closure itself, and the optional chaining is only evaluated each time clos is called, so it will evaluate to nil if currentBottle is nil… but will be evaluated to non-nil and will call jiggle() if we call clos() at a later time at which point currentBottle became non-nil.

    0 讨论(0)
  • 2020-12-03 14:21

    Okay, another approach. This is because closures in Swift have Implicit Returns from Single-Expression Closures. Because of the optional chain, your closure has a return type of Void?, so:

    let clos = {() -> Void? in self.currentBottle?.jiggle()}
    
    0 讨论(0)
  • 2020-12-03 14:30

    Letting the closure type be inferred seems to work as well.

    let clos2 = { currentBottle?.jiggle() }
    clos2() // does a jiggle
    

    But I'm pretty sure this is just the compiler assigning a type of () -> ()?

    0 讨论(0)
提交回复
热议问题