Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Import modules without an Xcode project in Swift

I am using the command line to create swift files and using the "swift" command in order to run one of them. However I would like one file to be able to access functions from another file. If this were C then I could use the #include macro and specify where the file is. But Swift's import statement doesn't seem to allow that. There should be a way and I would like to know how to do it.

for example:

If I have a file with a function in it and then I make another file that uses that function. How do I allow it to use it?

// file1.swift
import Foundation

func sayHello() -> String {
    return "hello"
}

// file2.swift
import file1  // <-- trying to import file1 but it doesn't work

println(sayHello())

Once the files have been made I then write "swift file2.swift" in terminal. But it tells me..

error: no such module 'file1.swift'

clearly the swift compiler is looking for a module. How do I make file1 into a module? I've seen some solutions but they all take place in Xcode. What I'm looking for is to do it all in the command line.

like image 686
DerrickHo328 Avatar asked Mar 17 '15 01:03

DerrickHo328


People also ask

How do I manually import framework in Xcode?

To include a framework in your Xcode project, choose Project > Add to Project and select the framework directory. Alternatively, you can control-click your project group and choose Add Files > Existing Frameworks from the contextual menu.

What is swift H?

${Your project name}-Swift. h is for objc based project to use swift code I remember. It is generated by XCode, to translate swift code to a header file for objc to import. If you don't need to use swift in objc project, you don't need it. As you can see you are simply a swift project, everything is swift.


1 Answers

// file1.swift
func sayHello() -> String {
    return "hello"
}

// main.swift
println(sayHello())

and then from the terminal:

$ swiftc file1.swift main.swift 
$ ./main 
hello
like image 55
ksenks Avatar answered Oct 20 '22 19:10

ksenks