Rules of Swift Initializers


Rule 1: A designated initializer must call its immediate superclass designated initializer
Rule 2: A convenience initializer must calls initializers of the same class
Rule 3: A convenience initializers must ultimately call the designated initializer

Simple Case:















Complex Case

























Reference

Constructs in Objective C and Swift

Classes, Structs and Enums are called Constructs and all three of them allow your program to store, organize or manipulate data in different ways with different capabilities.

Classes
  • General Purpose, flexible construct that becomes the building blocks of your program code.
  • Have properties and methods that provide data storage and functionality to constructs
  • Can use inheritance
  • Can use initializers and de-initializers when setup or tear down when they are created or destroyed.
Structs
  • Structs in Swift can have Properties and Methods (Swift Only)
  • Can use initializers (Swift Only)
  • No Inheritance
  • Passed by copy ( this can be advantage/disadvantage based on the needs)
Enums:
  • Way to group related elements
  • Can include functions (Swift only)
  • Can use initializers (Swift only)

Operators in Objective C and Swift

Common for Objective C and Swift
  • Assignment Operator ( = )
  • Arithmetic Operator
    • addition +,
    • Subtraction -, 
    • Multiplication *,  
    • Division /
  • Remainder (Modulo) Operator %
  • Unary plus operator (+), Unary minus operator (-), unary operator is prepended directly on the value it operates on.
  • compound assignment/short hand operators (x+=y, x-=y, x*=y, x/=y, x%=y, x&=y, x|=y, x^=y)
  • Increment (++) & decrement operator (—) {int x=9, int y: y= ++x , y = - - x } (Removed in Swift 3)
  • Relational/Comparison operators 
    • Equal to (a == b)
    • Not equal to (a != b)
    • Greater than (a > b)
    • Less than (a < b)
    • Greater than or equal to (a >= b)
    • Less than or equal to (a <=  b)
  • Logical Operator 
    • Logical Not (!a)
    • Logical AND (a && b)
    • Logical OR (a || b)
  • Ternary Conditional Operator ( if condition? expression 1 : expression 2 )
Swift Only
  • Range Operator 
    • Closed Range Operator '1…10', includes 1 and 10 in this range.
    • Half Open Range Operator '1..~10 , includes 1 but not 10
  • Nil-Coalescing Operator (x??y)
The nil-coalescing operator (x ?? y) unwraps an optional x if it contains a value, or returns a default value y if x is nil. The expression a is always of an optional type. The expression y must match the type that is stored inside x.

The nil Coalescing operator is shorthand for the below code:

x != nil ? x! : y

The code above uses the ternary conditional operator and forced unwrapping (x!) to access the value wrapped inside a when x is not nil, and to return x otherwise. The nil-coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form.

Guard in Swift

Guard statement is similar to IF statement except the fact that body of code executes when the condition in guard statement is evaluated to false.

var citizenAge:Int  //Declare a variable of type Integer

citizenAge = 65

guard citizenAge < 60  else {
// Here citizen age is 65, the guard condition is evaluated to false and the below statement is executed.
print("Senior Citizen")
return
}
print("Not a Senior Citizen") // this is executed when guard condition is true.

Guard Statement can also be used for optional binding

var playerScore:Int?    //Declare a variable a of type Optional Integer, which might or might not have value (for e.g if player did not bat, he might not have any score)

func updatePlayerScore (playerScore:Int?){
    guard let score =  playerScore else {
        print(“Player did not bat“)
        return 
    }
    print("Player score is \(score)")
}
  • Unlike if statement values assigned in the Guard statement are still available after the Guard statement through out the remaining scope that encloses the Guard Statement
  • Guard Statement are typically written at the top of the enclosing scope

Swift Data Types

There are two fundamental data types in Swift

Value Types 
  • Int, Floating-Points, Booleans, Characters, Strings , Arrays, Dictionaries and Tuples (which are implemented as Structures)
  • Optionals (which are implemented as Enumerations)
Reference Types
  • Classes
  • Functions and Closures 

Optionals in Swift


var a : Int            // create a swift variable of type int
var b = a + 10      //compiler will thrown an error because a is not initialized

Alternative to above

When your using ‘?”/optional , that means your explicitly telling the compiler that a may or may not have the value.

var a : Int?
var b = a! + 5     // the compiler suggest to unwrap the optional, this is called force unwrapping and program will crash if in case a does not have value so force unwrapping of optionals is always dangerous and should not do it unless your sure about var holding a value.

then what is the safe way to deal with optionals? answer is optional binding 

if let nonOptionalValue = a {
var b = nonOptionalValue + 5  // if a is nil, this statement is not executed and force unwrapping is not required in this case because we knew that a is not nil and has a value for sure.

}

Pointers

In Objective C all objects are referenced using pointers:

A pointer is a variable which stores memory address instead of value itself.

how big is int, 4 bytes
how big is char, 1 byte
how big is String, image or video?  we often don’t know and it might even change during our program so we need more flexible way to manage objects and pointers are one way of allowing us to do that.

Using pointers allows us to pass around the objects (just by passing around the address of object) without having need to copy them which is time consuming and inefficient  

E.g.   NSString* welcomeString;
         NSDate* todayDate;

welcomeString = @“Welcome to Objective C”;

Here the string 'Welcome to Objective C’ string is not directly stored in ‘welcomeString’ instead the address/memory location of 'Welcome to Objective C' is stored in ‘welcomeString which is contrary to 'int highScore = 100’ where ‘highScore’ variable directly stores value. ( this is because objects are more complex than primitive types)

if you want to make and use of simple object, we need pointers to reference them.
Note: Explicit use of pointers in Swift is not required unlike Objective C. e.g let someInstance = SomeClass ( ) whereas in objective C it is SomeClass *someInstance = [SomeClass alloc] init];