Cheatsheet Swift - Organize Code

May 15, 2019
swift cheatsheet

Organize Code

This cheat sheet for Swift 5 contains ways of organising code to improve reusability, readability, extensibility and maintainability.

Function

Declaration

func add(a: Int, b: Int) -> Int {
    let ans = a + b
    return ans
}
func sub(a: Int, b: Int = 9) -> Int {
    let ans = a - b
    return ans
}

Call

print(add(a: 1, b: 2))

3

print(sub(a: 9))

0

print(sub(a: 10, b: 8))

2

Closure

Declaration

let add: (Int,Int)->Int = { 
    (a: Int, b: Int)->Int in 
    let ans = a + b
    return ans
}

Call

print(add(1,2))

3

Class

Declaration

class Rectangle {}

Properties

class Rectangle {

    var length: Int = 0
    var breadth: Int = 0
    
}

Constructor

class Rectangle {
    //..
    
    init(length: Int, breadth: Int){
        self.length = length
        self.breadth = breadth
    }
}

Destructor

class Rectangle {
    //..
    
    deinit {
        
    }
}

Object Creation

let a = Rectangle(length: 4, breadth: 10)

Class Method Declaration

class Rectangle {
    //..
    
    private func isPositive(number: Int)->Bool{
        return number >= 0
    }
    
    func setLength(length: Int){
        self.length = length
    }
    
}

Interface Declaration

protocol Shape {
    func area() -> Int
}

Implementing Interface

class Rectangle: Shape {
    //..
    
    func area()->Int{
        return length*breadth
    }
}

Abstract Class Declaration

protocol Shape {
    func area() -> Int
    func printConsole()
}

extension Shape {
    func printConsole(){
        print("Area is: \(area())")
    }
}

class Rectangle: Shape {
    //..
    
    func area()->Int{
        return length*breadth
    }

    func print(){
        printConsole()
    }
}

Call Instance Method

let a = Rectangle(length: 4, breadth: 10)
a.print()

Area is: 40

Inheritance

class Activity {
    func onCreate(){
        print("Activity")
    }
}

class MainActivity : Activity {
    override func onCreate(){
        super.onCreate()
        print("MainActivity")
    }
}

DTO

struct Point {
    var xCoord: Float
    var yCoord: Float
}

Enumeration

enum Color { case RED, GREEN, BLUE }
let current: Color = Color.RED
print(current)

RED

Generics

class Rectangle<T:Numeric> {
    var length: T
    var breadth: T
    
    init(length: T, breadth: T){
        self.length = length
        self.breadth = breadth
    }
    
    func setLength(length: T){
        self.length = length
    }

    func setBreadth(breadth: T){
        self.breadth = breadth
    }

    func area() -> T {
      return length*breadth
    }
}

Generic Object Creation

let a = Rectangle<Float>(length: 1.1, breadth: 1.1)
print(a.area())

1.21

comments powered by Disqus