implicit return in a closure causing an error

前端 未结 2 919
情书的邮戳
情书的邮戳 2020-12-12 06:10
Error: Cannot convert the expression type (String, MyType) to ()

From the following code

Test(method: {[weak self] (message: String         


        
相关标签:
2条回答
  • 2020-12-12 06:19

    The implicit return is returning the result of your callback() method. That return value conflicts with the closure's return value of void. You thus need an explicit, if ugly, return.

    0 讨论(0)
  • 2020-12-12 06:38

    Not sure how to handle the above without having to have the dummy return statement, any advise.

    You have solved the problem beautifully. Anonymous functions automatically use a one-line function body as a return value, so to prevent that from causing a type mismatch with the expected return type (Void) you have to add another line of code so that it is not a one-line function body. The dummy return statement, which itself returns Void, is a great way to handle it; I would just use that and move on. There are some snazzier workarounds but what you have is precisely what I would do.

    EDIT: To understand the source of the type mismatch, try this:

    struct Test {
        func voider() -> Void {}
    }
    
    let testMaybe = Optional(Test())
    let result = testMaybe?.voider()
    

    Now result is not a Void; it's an Optional wrapping a Void. That is what's happening to you; a Void is expected but your one-line anonymous function returns an Optional wrapping a Void. By adding another line that returns Void explicitly, you solved the problem.

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