Muhammad Shauket
Muhammad Shauket

Reputation: 2778

Assign Function to other class variable

Sorry for if this asked many times, I tried many solution none of the work for me. I am doing a very basic thing like this way.

class NotificationModel: NSObject {
   var selector = (() -> Void).self
}

Other class.

class TestNotificationClass1 {
   init() {
      var model = NotificationModel.init()
      model.selector = handleNotification //error is here
   }

   func handleNotification() -> Void {
    print("handle function 1")
   }
}

Error description: Cannot assign value of type '() -> Void' to type '(() -> Void).Type'

Upvotes: 2

Views: 81

Answers (1)

rmaddy
rmaddy

Reputation: 318814

If you want selector to be able to hold any function with no parameters and no return value then change its declaration to:

var selector: (() -> Void)?

This also makes it optional. If you don't want it to be optional then you need to add an initializer to NotificationModel that takes the desired selector as a parameter as shown below:

class NotificationModel: NSObject {
    var selector: (() -> Void)

    init(selector: @escaping () -> Void) {
        self.selector = selector

        super.init()
    }
}

class TestNotificationClass1 {
    init() {
        var model = NotificationModel(selector: handleNotification)
    }

    func handleNotification() -> Void {
        print("handle function 1")
    }
}

Upvotes: 2

Related Questions