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
cd
directory_name
(orcd ..
to go back)
$ swift hello.swift Hello, world!
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 Hello, world!
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 aname
and 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) usinglet
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 constantsmyName
,mySurname
.
Running it using REPL:
$ swift Welcome to Apple Swift. Type :help for assistance. 1> func greet(name: String, surname: String) { 2. print("Greetings \(name) \(surname)") 3. } 4> 5> let myName = "Homer" myName: String = "Homer" 6> let mySurname = "Simpson" mySurname: String = "Simpson" 7> greet(name: myName, surname: mySurname) Greetings Homer Simpson 8> ^D
Press CTRL+D to quit from REPL.