In the Swift REPL, how to import (a.k.a. load, evaluate, require) a typical text *.swift file?
I want to use the code from this file:
~/src/Foo.swift
Syntax like this doesn't work:
import ~/src/Foo.swift
For comparison:
An equivalent solution in the Swift REPL for a framework is:
import Foundation
An equivalent solution in the Ruby REPL for a *.ruby file is:
require "~/src/foo"
These are similar questions that are /not/ what I'm asking:
How to use/make a Swift command-line script, executable, module, etc.
How to use/make an XCode playground, project, library, framework, etc.
How to launch the REPL with a pre-existing list of files.
You need to use -I, so if your modulename.swiftmodule file is in ~/mymodules than launch swift with
swift -I ~/mymodules
and then you will be able to import your module
import module name
Should be that easy
In swift,you can't import a typical *.swift file.
For Import Declaration
can only be the following syntax:
“ import-declaration → attributesopt import import-kindopt import-path
import-kind → typealias| struct| class| enum| protocol| var| func
import-path → import-path-identifier| import-path-identifier.import-path
import-path-identifier → identifier| operator”
From: Apple Inc. “The Swift Programming Language (Swift 2)”。 iBooks.
which can be described as these formats:
import
module
importimport kind
module
.symbol name
importmodule
.submodule
import head.swift
is incompatible with import import-kind module.symbol-name
Usually compile the files you want to import as a framework.Then it can be regarded as a module. use -F framework_directory/
to specify 3rd-party frameworks' search path.
Create a file. For example:
// test.swift import headtest print("Hello World")
open your terminal
- goto the directory where you create the file.
execute command line
swift -F headtest test.swift
And done.
Simply insert the shebang line at the top of your script:
#!/usr/bin/env xcrun swift
It looks like it's not possible to import file and get Xcode to use REPL for it using specifications you gave. I think you can still do it creating a proper framework, but it's not exactly what you was looking.
You can copy/paste the source code into the repl and execute it. Not ideal, obviously, but sometimes useful.
来源:https://stackoverflow.com/questions/27872589/swift-repl-how-to-import-load-evaluate-or-require-a-swift-file