Your first Swift program
suggest changeWrite your code in a file named hello.swift:
print("Hello, world!")
- To compile and run a script in one step, use
swiftfrom the terminal (in a directory where this file is located):
To launch a terminal, press CTRL+ALT+T on Linux, or find it in Launchpad on macOS. To change directory, enter cddirectory_name (or cd .. to go back)
swift hello.swift
A compiler is a computer program (or a set of programs) that transforms source code written in a programming language (the source language) into another computer language (the target language), with the latter often having a binary form known as object code. (Wikipedia)
- To compile and run separately, use
swiftc:
swiftc hello.swift
This will compile your code into hello file. To run it, enter ./, followed by a filename.
./hello
- Or use the swift REPL (Read-Eval-Print-Loop), by typing
swiftfrom the command line, then entering your code in the interpreter:
Code:
func greet(name: String, surname: String) {
print("Greetings \(name) \(surname)")
}
let myName = "Homer"
let mySurname = "Simpson"
greet(name: myName, surname: mySurname)
Let’s break this large code into pieces:
func greet(name: String, surname: String) { // function body }- create a function that takes anameand asurname.print("Greetings \(name) \(surname)")- This prints out to the console “Greetings “, thenname, thensurname. Basically\(variable_name\)prints out that variable’s value.let myName = "Homer"andlet mySurname = "Simpson"- create constants (variables which value you can’t change) usingletwith names:myName,mySurnameand values:"Homer","Simpson"respectively.greet(name: myName, surname: mySurname)- calls a function that we created earlier supplying the values of constantsmyName,mySurname.
Running it using REPL:
swiftfunc greet(name: String, surname: String) {print("Greetings \(name) \(surname)")}let myName = "Homer"let mySurname = "Simpson"greet(name: myName, surname: mySurname)
Press CTRL+D to quit from REPL.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents