gpt4 book ai didi

swift - 将函数分配给其他类变量

转载 作者:可可西里 更新时间:2023-11-01 01:06:57 24 4
gpt4 key购买 nike

很抱歉,如果这个问题问了很多次,我尝试了很多解决方案都没有用。我正在用这种方式做一件非常基本的事情。

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

关于swift - 将函数分配给其他类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57566254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com