Swift's REPL (read-eval-print Loop) environment allows us to use Swift for simple, interactive programming. This means that every input sentence is executed and output immediately. This is common in many interpretive languages and is well suited for learning the characteristics of a language.
To start the REPL environment, use Swift's command-line tool, which is in thexcrunform of a command parameter. First we need to confirm that the version of Xcode used is 6.1 or higher, and if not, you can select it in the Command line Tools Locations in the Xcode settings. Then we can start the REPL environment by typing it on the command linexcrun swift.
In Xcode 6.0, there is no SDK for OSX 10.10, and the command line execution of Swift REPL requires the latest version of the OSX SDK. If we use the version of Xcode 6.0, the SDK ' MACOSX10.9.SDK ' does not support Swift's error will appear.
To point out, the REPL environment just behaves as if it were an instant interpretation, but its essence is to compile and run after each code entry. This limits the complexity of what we are not likely to do in a REPL environment.
Another use is to directly.swiftinput a file as a command-line tool, so that the code inside will be automatically compiled and executed. We can even add the.swiftpath of the command line tool at the top of the file, then change the file permissions to executable, and then execute the.swiftfile directly:
- Hello.swift
- #!/usr/bin/env Xcrun Swift
- println ("Hello")
-
- Terminal
- > chmod 755 hello.swift
- >./hello.swift
-
- Output:
- Hello
These features are exactly the same as other explanatory languages.
swiftAnother common place for Swift command-line tools is to compile and build executable binaries directly from the Xcode environment, relative to direct command execution. We can use itswiftcto compile, such as the following example:
- Myclass.swift
- Class MyClass {
- Let name = "Xiaoming"
- Func Hello () {
- println ("Hello \ (name)")
- }
- }
-
- Main.swift
- Let object = MyClass ()
- Object.hello ()
-
-
- > Xcrun SWIFTC myclass.swift main.swift
A named executable file will be generatedmain. Operation:
- >./main
- Output:
- Hello xiaoming
Using this method, we can write some command-line programs with Swift.
Finally, the use case for a Swift command-line tool is to generate assembly-level code. Sometimes we want to make sure what the optimized assembler code actually does.swiftcparameters are provided to generateasmthe level of assembly code:
- Swiftc-o hello.swift > Hello.asm
Swift's command-line tools also have a number of powerful features that readers of interest may wish to usexcrun swift --helpas well asxcrun swiftc --helpto see what other parameters are available.
(Article source: Swifter Wang Wei)
Swift command-line tools