如何在 Swift 中调用带有函数指针参数的函数?
how to call a function that takes a function pointer argument in Swift?
根据 Apple 文档:
When calling a function that takes a function pointer argument, you can pass a top-level Swift function, a closure literal, or 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
}
)
但我在 Xcode 中收到一条错误消息:(copyDescription:customCopyDescription 错误)
A C function pointer can only be formed from a reference to a 'func' or a literal closure
如苹果文档中所述,customCopyDescription 可以作为顶级 swift 函数传递,但文档中似乎有问题。
如何将 customCopyDescription 函数作为 swift 函数(不是闭包文字)传递给 CFArrayCallBacks?
customCopyDescription
需要是 free 函数,而不是方法。当我将您的代码复制到 Xcode 时,只有当 customCopyDescription
在 class 中时我才会收到错误消息,否则不会。
添加占位符 return 值并将 customCopyDescription
置于文件范围后,代码编译没有问题
根据 Apple 文档:
When calling a function that takes a function pointer argument, you can pass a top-level Swift function, a closure literal, or 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
}
)
但我在 Xcode 中收到一条错误消息:(copyDescription:customCopyDescription 错误)
A C function pointer can only be formed from a reference to a 'func' or a literal closure
如苹果文档中所述,customCopyDescription 可以作为顶级 swift 函数传递,但文档中似乎有问题。
如何将 customCopyDescription 函数作为 swift 函数(不是闭包文字)传递给 CFArrayCallBacks?
customCopyDescription
需要是 free 函数,而不是方法。当我将您的代码复制到 Xcode 时,只有当 customCopyDescription
在 class 中时我才会收到错误消息,否则不会。
添加占位符 return 值并将 customCopyDescription
置于文件范围后,代码编译没有问题