Swift

1. Open Source

2. Server side apps -> instead of node / python

3. Apps for Apple TV, iPhone / iPad etc.

4. Modern features -> functional programming

 

Lamda -> Fn ->  Scala, Julia

Playground vs REPL

// READ / EVAL / PRINT / LOOP

Facts

Swift 4 -> Still compiles in Swift 5

Past wasn't true

Object Oriented Programming -> Different

No Main required 

Data Types

Swift vs JavaScript vs Java 

C / C++ -> Compiled -> Machine Code -> RUN

JAVA / C# -> Partial compiled -> ByteCode -> JVM JIT ComILE ->Run

Javascript / RUby -> SourceCode -> Interpret -> Run

C / C++ -> Compiled -> Machine Code -> RUN

JAVA / C# -> Partial compiled -> ByteCode -> JVM JIT ComILE ->Run

DataTypes

Data Type Memory Consumption
Int Platform-dependent
String Variable
Double 8 bytes
Float 4 bytes
Bool 1 byte
Character 1 byte

Constants

let vs var

let -> constant

var -> variable

 

 

Warning vs Error

Initialization

Implicit Conversion

let a = 2

let b = 6

 

result:Double = a/ b

int = double?

Implicit -> Compiler automatic

Explicit -> Your force 

Default Initialization

var name: String // defaultl not "'

var a: Int // none

 

Optional

 

Int // never nil

Int? // can be nil

String? / can be nil

 

means may have a value or maynot

 

Int? -> can be nil

 

nil only used be optional

Handling optional

Wrapping it

 

 

can be value?

no value

Text

// swift
if optionalInt !=nil {

	var unwrappedInt = optionalInt!

}

if (variable != nil) {

print(variable)

} else {

print("value is nil")

}

Halndling option

// optional binding


if let unwrappedString = unwrappedString {
	print(unwrappedString)
}   else {
	// no value exists
}

Swift Collections

Array

Dictionary

Set

 

what about DSA?

0 1 2 3
Alpha Beta Gamma Theta

.append()

.removeAt()

var array:[String] =[]

Rules

Paranthesis optional in if

curly braces mandatory

if vs switch

What's different in Swift:

1. No fallthrough but commas

2. Ranges allowed with ...

(1...10) -> inclusive or exclusive

Loops

1. While (condition) {

2. repeat while 

3. for loop

items = ["a","b","c"]

for char in items {

print(char)

}

Range operators

 

0...10

0..<10

 

strideTo vs SrideThroguh

 

for number in stride {

 

}

String concatenation

Interppolation \()

 

___ is listening to ____

 

\(name) is listening to \(song)

 

Harnoor is listening to Bulleya

function

func doSomething() {

print("this funcion call worked")

}

 

function(outside inside:Int) {

}

enum

Set of options to use

easy to use in switch

Struct 

1. String is a struct not a class

2. very powerful

 

 

struct Employee {

// properties and methods

var employeeName: String

}

// similar to classes 

// no inheritance

 

Struct vs Class

// Class = reference type

// struct = value type

 

// class -> Inheritance

// struct -> cannot

 

// class -> needs init and toString

// struct doesn't

Dictionary

 

Map 

 

"0" -> "Harry"

"20 -> "Potter"

 

 

 

//swift

if let result = dictionary["0"] {

print(result)

else {

print("nomatch")

}

// remove by setting to nil

Typles / Sets

var simpleTuple = (123 ,"hello", 12.12)

 

purpose: return multiple values 

Lamda / Closures

function ({code})

function ({Element -> Bool}) -> Bool

 

func({Int -> Int})

Protocols

defining Rules -

no code 

Implemet multiple protocols

// swift
protocol MyProtocol {

	func showMessage()
    var name: String { get / set }

}

Adopt vs Conform

Adopt -> using 

Conforming -> using methods from interface

Errors

enum ServerSerror {

case noConnection

case HTTPError

case AuthError

}

or implemnt Error protocol

throws keyword

 

// swift


func checkHTTP(serverNumber: Int) -> String {

	switch serverNumber {
    
    	case 1:
        	print("No connectoin")
         case 2:
         	print("auth failed")
    
   		default:
        pritn("can't find that server")
        }
        return "Success"
    }

}
// swift


func checkHTTP(serverNumber: Int) throws -> String {

	switch serverNumber {
    
    	case 1:
        	print("No connectoin")
            throw ServerERror.noconnection
         case 2:
         	print("auth failed")
    
   		default:
        pritn("can't find that server")
        }
        return "Success"
    }

}

// next part handle it

if let result = try? checkStatus(serverNumber:1){
print(result)
}

Guard & Defer

guard -> if else

1. use case -> optianl parameters

 

 

 

func processInfo(param1: String?, param2: String?) {
	// if null or if let
    
    guard condition else {
    	what if not true
    }

	// do nothing if tru
    
    guard controller.isActive else { return }
    
    guard let unwrappedVal = optionalVal else {
    	return
    }
}
func processInfo(param1: String?, param2: String?) {
    // Guard statement to unwrap optional parameters
    guard let param1 = param1, let param2 = param2 else {
        // Handle the case where either param1 or param2 is nil
        print("Error: One or both parameters are nil")
        return
    }
    
    // If we reach this point, both param1 and param2 have values
    
    // Now you can use param1 and param2 safely
    print("param1: \(param1), param2: \(param2)")
    
    // Example: Concatenate the parameters
    let concatenatedString = param1 + param2
    print("Concatenated string: \(concatenatedString)")
    
    // Or perform any other operations with the unwrapped parameters
}

Defer

func processServer() {

	server. open()
    
    defer {
    
    	server.close()
    }
    
    // guarantee it will be closed irrespective of problems in code later

}

Struct vs Clases

 

1. Value type vs Reference type

2. Struct -> init included but not in class

3. 

 

 

example -> make object equal both wil change

Functionality with Extensions

extension String {

	func removeSpace() -> String {
  
	   	let filteredChars = self.filter{$0 != " "}
        return String (filteredChaacters)
    }

}

Stored vs Computed Properties

var count: Int {

get {

return a + 500 * b +500

}

set {

}

}

 

print(count)

Inheritance Example

import Foundation

class Story1 {

    static func printEmployeeSalary(_ employee: Employee) {
        switch employee.employeeType {
        case "Contractor":
            print("Contractor Salary: $100,000")
        case "Full Time":
            print("Full Time Salary: $150,000")
        case "Intern":
            print("Intern Salary: $50,000")
        default:
            break
        }
    }

    static func printHelloWorld() {
        for i in 1...5 {
            print("Hello World \(i)")
        }
    }

    static func calculate(_ input1: Int, _ input2: Int) -> Int {
        return input1 + input2
    }

    static func calculate2(_ a: Int, _ b: Int) {
        print(a + b)
    }
}

class Employee {
    var employeeName: String
    var employeeType: String
    var employeeId: Int

    init(employeeName: String, employeeType: String, employeeId: Int) {
        self.employeeName = employeeName
        self.employeeType = employeeType
        self.employeeId = employeeId
    }

    var description: String {
        return "Employee Name: \(employeeName)\nEmployee First Character: \(employeeType)\nEmployee ID: \(employeeId)"
    }
}

class Contractor: Employee {
    let salary = "$100,000"

    override var description: String {
        return super.description + "\nSalary = \(salary)"
    }
}

class Intern: Employee {
    let salary = "$50,000"

    override var description: String {
        return super.description + "\nSalary = \(salary)"
    }
}

class FullTime: Employee {
    let salary = "$150,000"

    override var description: String {
        return super.description + "\nSalary = \(salary)"
    }
}

Documentations

found on apple docs & in xcode

Debugging

Made with Slides.com