2

According to Apple Documentation:

When calling a function that takes a function pointer argument, you can pass a top-level Swift function, a closure literal, or nil.

I've tried this example from Apple Documentation: 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
}
)  

but I got an error message in Xcode: (copyDescription: customCopyDescription error)

A C function pointer can only be formed from a reference to a 'func' or a literal closure

As mentioned at apple documentation , customCopyDescription can be passed as a top-level swift function, but it's seems like something is wrong in the documentation.

How to pass the customCopyDescription func to the CFArrayCallBacks as a swift function(not a closure literal)?

Shadi Asi
  • 157
  • 13
  • 1
    Did you put that inside a class definition? `customCopyDescription` needs to be a *global function.* – See also [How to use instance method as callback for function which takes only func or literal closure](https://stackoverflow.com/questions/33260808/how-to-use-instance-method-as-callback-for-function-which-takes-only-func-or-lit). – Martin R Feb 04 '18 at 11:07

1 Answers1

6

customCopyDescription needs to be a free function, not a method. When I copied your code into Xcode I got the error message only when customCopyDescription was inside a class, not otherwise.

Once placeholder return values are added and customCopyDescription is placed at file scope, the code compiles without a problem

Rich Tolley
  • 3,812
  • 1
  • 30
  • 39