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

How to initialize and use function pointer in Swift

假设我在 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 SO post and this 教程,但无论如何我都无法将它用于 (Void) -> Void 函数...

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

self.funcPointer = self.func1

后续错误

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

可以通过声明 funcPointer 隐式解包可选

来修复
internal final var funcPointer: (() -> Void)!