Optional chaining in Swift Closure where return type has to be Void

前端 未结 1 1978
不思量自难忘°
不思量自难忘° 2020-11-28 16:22

I am creating a doubly-linked-list of scripts (MSScripts) that are supposed to have their own run() implementation, and they call the next script (

相关标签:
1条回答
  • 2020-11-28 16:44

    Optional chaining wraps whatever the result of the right side is inside an optional. So if run() returned T, then x?.run() returns T?. Since run() returns Void (a.k.a. ()), that means the whole optional chaining expression has type Void? (or ()?).

    When a closure has only one line, the contents of that line is implicitly returned. So if you only have that one line, it is as if you wrote return weakSelf.rscript?.run(). So you are returning type Void?, but dispatch_async needs a function that returns Void. So they don't match.

    One solution is to add another line that explicitly returns nothing:

    dispatch_after(time, dispatch_get_main_queue()) {
        weakSelf.rscript?.run()
        return
    }
    
    0 讨论(0)
提交回复
热议问题