Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Swift Interface from Objective-C Header from Command Line

Tags:

swift

interop

In Xcode, for any Objective-C header, we can view the Generated Interface, which shows how it is seen by Swift in interop.

I'd like to generate that from the command line. Any idea how to do it?

Bonus task: The header should be precompiled first, so all #imports should be replaced already.

like image 403
fabb Avatar asked May 08 '16 09:05

fabb


1 Answers

Invoke interpreter command :type lookup on the module you are trying to inspect.

Suppose you have a header file named header.h. Put it into a separate directory, so that the interpreter would recognise it as a module. Also create a modulemap in the same directory. Let's call this directory Mod:

./
./Mod/
     /header.h
     /module.modulemap

Fill in the modulemap with the following:

module Mod {
  header "./header.h"
  export *
}

Once it's done, issue a command like this:

echo "import Mod\n:type lookup Mod" | swift -I./Mod | tail -n+2 >| generated-interface.swift

Alternatively, you might want use a command like this with equal effect:

echo "import Mod\n:print_module Mod" | swift -deprecated-integrated-repl -I./Mod >| generated-interface.swift

It's broken down as follows:

  • first we echo the script to be executed: import module and type-lookup it;
  • then we launch the interpreter and feed the script into it; the -I argument helps it find our module, which is crucial;
  • then we cut off the “Welcome to Swift” part with Tail
  • and write the result into generated-interface.swift.

While running the above commands, make sure your working directory is set to one level higher than the Mod directory.

Note that the output might not be exactly the same as from Xcode, but it's very similar.


Just for the record, if you want to produce the interface from a Swift file, then it's just this:

swiftc -print-ast file.swift
like image 63
Accepted Answer Avatar answered Nov 13 '22 08:11

Accepted Answer