Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

swift - implicit return in a closure causing an error

Error: Cannot convert the expression type (String, MyType) to ()

From the following code

Test(method: {[weak self] (message: String) in self?.callback(message)}, instance: self)

and if I add a return statement, it works, and the error goes away

Test(method: {[weak self] (message: String) in self?.callback(message); return}, instance: self)

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

Here's my class Test

public class Test { 
    private var instance: AnyObject?
    private var method: ((message: String) -> ())?

    public init(method: (String -> ())?, instance: AnyObject) {

    }
 }


Edit

I've done a playground based minimalistic example (please copy paste for a test)

class Test {

    private var _method: ((String) -> ())?

    weak private var _instance: AnyObject?

    init(method: (String -> ())?, instance: AnyObject?) {
        _method = method
        _instance = instance
    }
}

class Another {

    func register() {
        //this doesn't need a return
        Test(method: {(message: String) in self.callback(message)}, instance: self)

        //this needs a return once I add [weak self]
        Test(method: { [weak self] (message: String) in self?.callback(message); return}, instance: self)
    }

    func callback(message: String) {
        println(message)
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...