Your first Swift program

Download swift eBook

Example

Write your code in a file named hello.swift:

print("Hello, world!")
  • To compile and run a script in one step, use 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
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)

  • 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
Hello, world!
  • Or use the swift REPL (Read-Eval-Print-Loop), by typing 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:

$  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.

Stats

Contributors: 8
2017-07-08
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook