Swift basics

Swift basics

Here are some of the basis of the Swift programming language

Comments

Comments are written using //, Similar to C/C++:

// This is a comment

Constants

Constants are declared using the let keyword:

let myConstant:Int = 1

Variables

Swift is a strongly typed language. Variables are declared using the var keyword as following this syntax:

var variableName:String = 'Hello'

Loops

Here is an example of a for loop:

for i in 1...5{
    // do something
}

Functions

Functions are defined using the func keyword. The type of the function parameters and its return values must be defined. Note that a function can have multiple return values.

func myFunction(var1:Type, var2:Type) -> (returnType1, returnType2) {
	// Function code
	return ...
}

The function can then be used as follows:

(ret1, ret2) = myFunction(var1: 2, var2: 4)

Function labelts

Labels can be added to improve functions readability:

func sum(of a :Int, and b:Int) -> Int {
    return a + b
}
let result = sum(of: 2, and: 3)
print("The sum is \(result)")

Classes

classes can be defined using the class keyword:

class MyClass {

}

Example

Here is an example that combines a bit of all the basics

import Foundation

class Person {

    // Properties
    var first_name:String
    var last_name:String
    var age:Int
    var bank_account_balance:Int

    // Constructor
    init(first_name:String, last_name:String, age:Int = 0) {
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
        bank_account_balance = 0
    }
    
    // Methods
    func self_introduction(){
        print("Hi, my name is \(first_name) \(last_name)")
    }

    func birthday(){
        age = age + 1
        print("Happy \(age)th birthday \(first_name)!")
    }
}

// Subclass of Person (inherits from Person)
class Employee : Person {

    var employee_number:String
    var salary:Int

    init(first_name:String, last_name:String, employee_number:String, salary:Int = 0){
        self.employee_number = employee_number
        self.salary = salary
        super.init(first_name:first_name,last_name:last_name)
    }
    
    func work(){
        bank_account_balance = bank_account_balance + salary
        print("\(first_name) worked for $\(salary) an hour, bank account balance is now $\(bank_account_balance)")
    }
}


var person1 = Person(first_name:"John", last_name:"Doe", age:23)
person1.self_introduction()
person1.birthday()

var employee1 = Employee(first_name:"Mark", last_name:"Smith", employee_number:"1234", salary:20)

// Example for loop
for _ in 1...5{
    employee1.work()
}