gpt4 book ai didi

swift - 如何在 Swift 中初始化和使用函数指针

转载 作者:搜寻专家 更新时间:2023-11-01 06:52:19 25 4
gpt4 key购买 nike

假设我在 Playground 上剪下了这段代码

import UIKit

internal final class TestClass {
internal final var funcPointer: () -> Void

init() {
self.funcPointer = self.func1() //Cannot assign value of type '()' to type '() -> Void'
}

internal final func func1() {
print("func1 is called!")
}
}

var testClass: TestClass = TestClass()
testClass.funcPointer()

为什么我在 init() 方法中得到显示的错误消息以及如何正确初始化函数指针?

我已经看到了this所以发布和this教程,但无论如何我没有让它为 (Void) -> Void 函数工作...

最佳答案

要将闭包分配给您必须删除括号的属性

self.funcPointer = self.func1

后续错误

self' used in method call 'func1' before all stored properties are initialized

可以通过声明funcPointer implicit unwrapped optional 来修复

internal final var funcPointer: (() -> Void)!

关于swift - 如何在 Swift 中初始化和使用函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56345383/

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