【问题标题】:how to call a function that takes a function pointer argument in Swift?如何在 Swift 中调用带有函数指针参数的函数?
【发布时间】:2018-02-04 10:55:27
【问题描述】:

根据苹果文档:

调用带有函数指针参数的函数时,您可以传递顶级 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
}
)  

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

C 函数指针只能由对 'func' 或文字闭包的引用构成

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

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

【问题讨论】:

标签: ios swift pointers function-pointers


【解决方案1】:

customCopyDescription 必须是 free 函数,而不是方法。当我将您的代码复制到 Xcode 中时,仅当 customCopyDescription 在类中时才收到错误消息,否则不会。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 2015-09-03
    • 2018-01-03
    • 1970-01-01
    • 2018-08-25
    相关资源
    最近更新 更多