Mike Mike - 3 months ago 17
Swift Question

Swift - Import Source File by Path?

I've been playing around with using Swift as a scripting language, as described here. When executing script files from the terminal in this way, is there a way to include other Swift files by path (i.e.

import /path/to/some/file.swift
)? I'm aware of the
import
statement, but that doesn't seem to accept a file path. In Ruby I would use a
require
statement, but I don't know if there is a Swift equivalent to this.

Answer

import only works with modules. If you need to import a module which is located somewhere besides the normal import search path, you can add another directory to the search paths by passing the -I flag to the compiler:

-I <value> Add directory to the import search path

If you're looking at just a .swift file, you'll need to compile that into a module before you can import it from a separate module or the REPL.