One-line closure without return type

前端 未结 2 2037

In Swift, if a closure holds only a single statement, it automatically returns the value returned from that single statement.

This does not feel very natural in all

相关标签:
2条回答
  • 2020-12-05 14:42

    What about this ... ;)

    @discardableResult func StringReturningFunc() -> String {
        return "Test String"
    }
    
    // Error: Cannot convert the expressions type '() -> $T0' to type 'String'
    let closure: () -> () = {
        StringReturningFunc()
    }
    
    0 讨论(0)
  • 2020-12-05 15:01

    The reason this happens is the shorthand for single line expression closures. There is an implicit 'return' in your closure as it is written.

    let closure: () -> () = {
        StringReturningFunc()
        return
    }
    

    Writing it like that should work

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