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 the directory that contains this file.
To launch a terminal, press Ctrl+Alt+T on Linux, or find Terminal in Launchpad on macOS. To change directory, enter cd directory_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 compiles your code into a file named hello. To run it, enter ./ followed by that 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)
The pieces are:
func greet(name: String, surname: String) { // function body }creates a function that takes anameand asurname.print("Greetings \(name) \(surname)")printsGreetings, thenname, thensurname.\(variableName)inserts that value.let myName = "Homer"andlet mySurname = "Simpson"create constants withlet. A constant's value cannot be changed. The names aremyNameandmySurname. The values are"Homer"and"Simpson".greet(name: myName, surname: mySurname)calls that function with the constantsmyNameandmySurname.
Running it using the REPL:
swift
func 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