0

I want to call this Objective-C function from Swift code.

The accepted answer on this question shows how to use an Objective-C class in Swift, not a function. Secondly, the Objective-C implementation in it is contained in a .m file, while the one I have linked above is a .h file.

What is the easiest way I can call an Objective-C function defined in a .h file from Swift?

Himanshu P
  • 9,586
  • 6
  • 37
  • 46
  • You always have an implementation, in your case a c-file, so that's not different compared the Objective-C link you posted. Otherwise the process seems very similar for a C file, google "swift call c function" – Joakim Danielson Sep 30 '19 at 11:20
  • I think that it's `C`'s function. `Objective-C` only have class and instance methods. – Cy-4AH Sep 30 '19 at 11:34
  • You need to include a C `.h` header in the project bridging header to make the C function visible to Swift. – Kamil.S Sep 30 '19 at 11:56

1 Answers1

0

As mentioned in the comments first you'll need to do all the usual steps for using Objective-C classes from Swift (bridging header, etc.) Then you'll already be able to call your function and you'd only need a bit of tweaking to make it more usable in Swift.

func CopyLaunchedApplicationsInFrontToBackOrder_Swift() -> [[String: AnyObject]]? {
    guard let cfarray = CopyLaunchedApplicationsInFrontToBackOrder() else {
        return nil
    }

    let array = unsafeBitCast(cfarray, to: NSArray.self) as [AnyObject]

    guard let result = array as? [[String: AnyObject]] else {
        return nil
    }

    return result
}

If your function is implemented in .h file it would be better to move implementation into a corresponding .m file leaving in .h only it's declaration:

@import Foundation;

CFArrayRef CopyLaunchedApplicationsInFrontToBackOrder(void);

It's also possible to put this declaration into your bridging header and leave implementation in the .h file, but that would be unusual making your code more error prone and harder to maintain.

Konstantin Oznobihin
  • 5,234
  • 24
  • 31