Title: Swift closure giving function to variable
Tags: swift;closures
Question: class ClassA {
var callback : (()-&gt;())?
func someAction() {
callback?()
class ClassB {
func caller() {
let a = ClassA()
a.callback = {
print("hello")
//d do stuff
}
I want to move the ClassB callback implementation to seperate function. as below
a.callback = somefunc()
But this is not possible as we are giving function to variable
And I dont want
a.callback = { somefunc() }
Is there a way to call a funtion if at all?
Comment: Just remove the parenthesis. a.callback = somefunc

Here is the accepted answer: Adding () to someFunc means that you are calling the function and this will evaluate to the return value of someFunc, which is Void.
You need to refer to the function directly, without calling it. Just remove the ():
a.callback = someFunc
Comment for this answer: How to call if the closure has parameters like (String, Int) -> Void
Comment for this answer: got it someFunc(st:id:)


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:12/14/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<swift><closures>', 'Title': 'Swift closure giving function to variable', 'ViewCount': 98, 'id': 53775086, 'user_AboutMe': '', 'user_AccountId': 2155272.0, 'user_DisplayName': 'pradeep', 'user_Reputation': 393.0, 'user_Views': 95.0, 'user_id': 1910671.0}}