首页 > 解决方案 > 将函数分配给其他类变量

问题描述

很抱歉,如果这被问了很多次,我尝试了很多解决方案,但对我没有任何作用。我正在以这种方式做一件非常基本的事情。

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

其他类。

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

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

错误描述:无法将类型 '() -> Void' 的值分配给类型 '(() -> Void).Type'

标签: swift

解决方案


如果您希望selector能够保存任何没有参数且没有返回值的函数,请将其声明更改为:

var selector: (() -> Void)?

这也使它成为可选的。如果您不希望它是可选的,那么您需要添加一个初始化器NotificationModel,它将所需的选择器作为参数,如下所示:

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")
    }
}

推荐阅读