There are a couple of ways in which you can quickly experiment with Swift code. The first is the Swift interactive Read Evaluate Print Loop (REPL). The REPL is a command line tool that evaluates our code as we write it. Developers who are used to interpreting languages will be comfortable using this tool.
To start the REPL, you will need to open a terminal prompt and enter the following command:
swift
You will be greeted with a prompt similar to the following:
Welcome to Swift version 3.0 ({your-swift-version}). Type :help for assistance 1>
From here, we can type in any Swift statement and hit Enter. The REPL will immediately execute our code. The following is an example:
1> var x = 10 x: Int = 10 2> x += 5 3> print(x) 15
To exit the REPL, type the following command:
:quit
We can also quickly test a Swift source file using the swift
command. To try this out, create a file named Hello.swift
, and put the following code in it:
print("Hello")
Now let's run the following command to execute this source file:
swift Hello.swift
You should see the message Hello
printed to the console. The REPL and Swift commands are extremely powerful tools, and you can do a lot more than just prototyping new code. If you find these tools useful, I would recommend spending time learning about the various advanced features.