如何在 Swift 中调用一个接受函数指针参数的函数?

Sha*_*Asi 2 pointers function-pointers ios swift

根据苹果文档:

当调用一个接受函数指针参数的函数时,你可以传递一个顶级 Swift 函数、一个闭包字面量或 nil。

我已经从 Apple 文档中尝试过这个例子:Apple Developer

func customCopyDescription(_ p: UnsafeRawPointer?) -> Unmanaged<CFString>? {
    // return an Unmanaged<CFString>? value
}

var callbacks = CFArrayCallBacks(
    version: 0,
    retain: nil,
    release: nil,
    copyDescription: customCopyDescription,
    equal: { (p1, p2) -> DarwinBoolean in
        // return Bool value
}
)  
Run Code Online (Sandbox Code Playgroud)

但我在 Xcode 中收到一条错误消息:(copyDescription:customCopyDescription 错误)

AC 函数指针只能由对“func”或文字闭包的引用构成

正如在苹果文档中提到的,customCopyDescription 可以作为顶级 swift 函数传递,但文档中似乎有些问题。

如何将 customCopyDescription 函数作为 swift 函数(不是闭包文字)传递给 CFArrayCallBacks ?

Ric*_*ley 5

customCopyDescription需要是一个自由函数,而不是一个方法。当我将您的代码复制到 Xcode 中时customCopyDescription,只有在类中时才会收到错误消息,否则不会。

一旦添加占位符返回值并将customCopyDescription其放置在文件范围内,代码就可以毫无问题地编译