简体   繁体   中英

Swift - Passing closure to method

I just started learning Swift after 2 years away from iOS development and I seem to be stuck into the closure as argument syntax. I have the following method in a class:

func onFollwersButtonTouched(cb: () -> Void) {
    self.onFollowingTouchedCb = cb
}

And I try to set this callback on another class:

cell.onFollowersTouchedCb({ () -> Void in

})

This code does not compile. The compiler error is:

Error:(115, 14) cannot convert the expression's type '() -> Void' to type '() -> Void'

And I have no idea what is going on. I have tried the syntax on Apple's Swift book but it was unsuccessful as well.

You should either call method with closure parameter:

cell.onFollowersTouched({ () -> Void in

})

or assign closure to variable:

cell.onFollowersTouchedCb = { () -> Void in

}

You are currently calling onFollowersTouchedCb with closure parameter, while has no parameters declared.

This:

cell.onFollowersTouchedCb({ () -> Void in

})

is not setting the closure. You need to perform an actual assign:

cell.onFollowersTouchedCb = {
    // Do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM