Write your code in a file named hello.swift
:
print("Hello, world!")
swift
from 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)
swiftc
:swiftc hello.swift
This will compile your code into hello
file. To run it, enter ./
, followed by a filename.
./hello
swift
from 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 a name
and a surname
.print("Greetings \\(name) \\(surname)")
- This prints out to the console “Greetings “, then name
, then surname
. Basically \\(**variable_name**\\)
prints out that variable’s value.let myName = "Homer"
and let mySurname = "Simpson"
- create constants (variables which value you can’t change) using let
with names: myName
, mySurname
and values: "Homer"
, "Simpson"
respectively.greet(name: myName, surname: mySurname)
- calls a function that we created earlier supplying the values of constants myName
, 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)