swift - 将函数分配给其他类变量
问题描述
很抱歉,如果这被问了很多次,我尝试了很多解决方案,但对我没有任何作用。我正在以这种方式做一件非常基本的事情。
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'
解决方案
如果您希望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")
}
}
推荐阅读
- azure - 新对象:找不到类型 [Microsoft.Open.AzureAD.Model.DomainFederationSettings]:验证程序集
- php - Laravel/Passport - 重新迁移后密钥不可用
- python - Django sorl:没有足够的值来解包(预期 2,得到 1)
- reactjs - Redux 错误:操作必须是普通对象。使用自定义中间件进行异步操作
- python - ModuleNotFoundError:没有名为“load_data”的模块
- android - 谷歌表格不适用于发布 apk 颤振
- php - 如何使 userEmail 外键连接到 Tbluser 模型中的 emailId
- c# - 在 C# 中拆分大字符串并将其中的值添加到列表中
- python - 没有在python的新文件中写入所有输出行
- c++ - 将子类转换为父类 C++