Wednesday, 31 July 2019

Difference between == and ===




https://stackoverflow.com/questions/24002819/difference-between-and

== operator checks if their instance values are equal, "equal to”.  Value equality
=== operator checks if the references point the same instance, "identical to"  Reference equality

=== : Classes are reference types, it is possible for multiple constants and variables to refer to the same single instance of a class behind the scenes. 


let person1 = Person(ssn: 5, name: "Bob")
let person2 = Person(ssn: 5, name: "Bob")

if person1 == person2 {//We are checking values of that variables
   print("the two instances are equal!")
}

if person1 === person2 {//Reference types we are checking references here.
   //It does not enter here
} else {
   print("the two instances are not identical!")
}

=== operator checks if the references point the same instance, "identical to". Since person1 and person2 have two different instance in Heap area, they are not identical 

let person3 = person1

P.S: Classes are reference types and person1's reference is copied to person3 with this assignment operation, thus both references point the same instance in Heap area.
if person3 === person1 {
   print("the two instances are identical!")
}

Range Operators: 
Closed Range: 1…5 gives 1, 2, 3, 4 and 5
Half-Open Range: 1..< 5 gives 1, 2, 3, and 4
One- sided Range :  1… gives 1 , 2,3… end of elements.  ,  …2 gives beginning… to 1,2


Type Aliases and Type Safety


https://www.tutorialspoint.com/swift/swift_data_types.htm

Type Aliases: You can create a new name for an existing type using typealias
Ex:
typealias Feet = Int
var distance: Feet = 100
print(distance)

Type Safety : Swift 4 is a type-safe language which means if a part of your code expects a String, you can't pass it an Int by mistake.

var varA = 42
varA = "This is hello"
print(varA)


Error:  main.swift:2:8: error: cannot assign value of type 'String' to type 'Int'


Optionals




Optionals:
which handles the absence of a value.

Ex: var perhapsStr: String?
The above declaration is equivalent to explicitly initializing it to nil which means no value −
var perhapsStr: String? = nil

var myString:String? = nil

if myString != nil {
   print(myString)
} else {
   print("myString has nil value")
}

Forced Unwrapping : just means putting an exclamation mark at the end of the variable.
Automatic Unwrapping : You can declare optional variables using exclamation mark instead of a question mark. 
Optional Binding : Use optional binding to find out whether an optional contains a value , and to make that value available as a temporary constant or variable. 
Ex: 
if let constantName = someOptional {
   statements
}

var myString:String?
myString = "Hello, Swift 4!"

if let yourString = myString {
   print("Your string has - \(yourString)")
} else {
   print("Your string does not have a value")
}
Output : Your string has - Hello, Swift 4!



Value type and Reference type




Value type and Reference type :
Good link : https://www.codementor.io/blog/value-vs-reference-6fm8x0syje

A value type instance keeps a unique copy of its data, for example, a struct or an enum
A reference type, shares a single copy of its data, and the type is usually a class.

Value Types
A value type instance is an independent instance and holds its data in its own memory allocation. There are a few different value types: struct, enum, and tuple.

In Swift, Array, String, and Dictionary are all value types.

In value types two variables address in the memory is different. 

Struct:
Let’s experiment with structs and prove that they’re value types:
// 1
struct Car {
    let brand: String
    var model: String
}

// 2
var golf = Car(brand: "Volkswagen", model: "Golf")
// 3
let polo = golf

// 4
golf.model = "Golf 2019"

// 5
print(golf)//Car(brand: "Volkswagen", model: "Golf 2019")
print(polo)//Car(brand: "Volkswagen", model: "Golf")

Even if polo is a copy of golf, the instances remain independent with their own unique data copies.

Enum
To check that enums are value types, add this code to the playground:
// 1
enum Language {
    case italian
    case english
}

// 2
var italian = Language.italian
// 3
let english = italian

// 4
italian = .english

// 5
print(italian) // english
print(english) // italian

Even if english is a copy of italian, the instances remain independent.

Tuple:
The last value type that we'll explore is tuple. A tuple type is a comma-separated list of zero or more types, enclosed in parentheses. You can access its values using the dot (.) notation followed by the index of the value.
You can also name the elements in a tuple and use the names to access the different values.
Add the following code to the playground:
// 1
var ironMan = ("Tony", "Stark")
// 2
let parent = ironMan

// 3
ironMan.0 = "Alfred"

// 4
print(ironMan) //("Alfred", "Stark")
print(parent) //("Tony", "Stark")



When to Use Value Types: 
Use value types when comparing instance data with == makes sense.
== checks if every property of the two instances is the same.

Reference Types:
reference type instances share a single copy of their data, so that every new instance will point to the same address in memory. A typical example is a class, function, or closure.


https://www.codementor.io/blog/value-vs-reference-6fm8x0syje


Create closure for to pass back data


Create closure for to pass back data

https://stackoverflow.com/questions/19343519/pass-data-back-to-previous-viewcontroller


Fix all collection view cells in center



Fix all collection view cells in center
       

 // https://stackoverflow.com/questions/40585822/how-to-center-align-the-cells-of-a-uicollectionview-in-swift3-0/41096743

Tuples, for-in, Dictionary Grouping, Filtering and Set



Set’s: 
sets are used to store distinct values of same types but they don’t have definite ordering as arrays have.(sets allow only distinct values.)

var someSet = Set<Character>()     //Character can be replaced by data type of set.

Set Operations
  • Intersection
  • Union
  • subtracting
let evens: Set = [10,12,14,16,18]
let odds: Set = [5,7,9,11,13]
let primes = [2,3,5,7]
odds.union(evens).sorted()
// [5,7,9,10,11,12,13,14,16,18]
odds.intersection(evens).sorted()
//[]
odds.subtracting(primes).sorted()
//[9, 11, 13]

Dictionary’s : 

var cities = [“Delhi”,”Bangalore”,”Hyderabad”]
var Distance = [2000,10, 620]

let cityDistanceDict = Dictionary(uniqueKeysWithValues: zip(cities, Distance))

Filtering
var closeCities = cityDistanceDict.filter { $0.value < 1000 } //Output : ["Bangalore" : 10 , "Hyderabad" : 620]


Higher order functions in Swift: Filter, Map, Reduce, flatmap, compactMap : 
higher order functions that can be used on collection types
higher order functions are functions that takes another function/closure as argument and returns it.



Dictionary Grouping

var cities = ["Delhi","Bangalore","Hyderabad","Dehradun","Bihar"]

var GroupedCities = Dictionary(grouping: cities ) { $0.first! }// Output : ["D" :["Delhi","Dehradun"], "B" : ["Bengaluru","Bihar"], "H" : ["Hyderabad"]]


JSON dynamic adding objects:
for a in res2 {
    if let nm = a["nm"] as? String, let uni = a["uni"] {
        self.dic[nm] = uni as? String
    }
}
print(self.dic)

for-in loop :
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

for (index, keyValue) in someDict.enumerated() {
   print("Dictionary key \(index) - Dictionary value \(keyValue)")
}

Tuples:
which are used to group multiple values in a single compound Value.

The values in a tuple can be of any type, and do not need to be of same type.
For example, ("Tutorials Point", 123)

Good link : https://medium.com/@abhimuralidharan/tuple-in-swift-a9ddeb314c79

EX:

Ex1)(“tuple", 1, true) //Tuple with different data types.

Ex2) var person = ("John", "Smith”)//Read values from tuple

var firstName = person.0 // John
var lastName = person.1 // Smith

Ex3)var point = (0, 0) //Assign values to tuple

point.0 = 10
point.1 = 15

point // (10, 15)

Note: Tuple are value types. When you initialize a variable tuple with another one it will actually create a copy.
var origin = (x: 0, y: 0)

var point = origin
point.x = 3
point.y = 5

print(origin) // (0, 0)

print(point) // (3, 5)


Removing viewcontrollers from navigation stack



When session expired move to login page : Removing viewcontrollers from navigation stack

//If session expaired move to login page
if message == "Session Expired" {
    DispatchQueue.main.async {
        //Check navigation stacks
        let navigationArray = self.navigationController?.viewControllers //To get all UIViewController stack as Array
        print(navigationArray!)//Prints navigation stacks

        //Remove all navigations
        self.navigationController!.viewControllers.removeAll()
        //Remoce particular VC navigation
        //self.navigationController?.viewControllers.remove(at: "insert here a number")

        //Check navigation stacks
        let navigationArray2 = self.navigationController?.viewControllers //To get all UIViewController stack as Array
        print(navigationArray2 as Any)//Prints nill

        //Check whether the user logined or not
        UserDefaults.standard.set(false, forKey: "isUserLoggedIn")
        //Clear user defaults
        SharedClass.sharedInstance.clearDataFromUserDefaults()

        let lvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LVC") as! LoginViewController
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window?.rootViewController = lvc                                
    }
}



What is UIWindow in iOS?



Window property :

var window: UIWindow?

the window property used to present the app’s visual content on the device’s main screen.
Normally, Xcode provides your app's main window. New iOS projects use storyboards to define the app’s views. Storyboards require the presence of a window property on the app delegate object, which the Xcode templates automatically provide. If your app does not use storyboards, you must create this window yourself.



Errors in iOS



Errors : 

1) Expression type '@lvalue CGRect' is ambiguous without more context

Code: 

Wrote this code in JSON response 
if status == "SUCCESS" {
    self.myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: self.subView.frame.width, height: tblViewDescArray.count*50)) //Error comes here self.subView.frame.width
    self.subView.addSubview(self.myTableView)

Solution :  https://stackoverflow.com/questions/51140220/swift-4-expression-type-value-cgrect-is-ambiguous-without-more-context

let width = self.subView.frame.width
                                
self.myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: Int(width), height: self.tblViewDescArray.count*50))

2) Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value


Solution : Here tableView IBOutlet not available in this VC.

Difference between == and ===

Difference between == and === https://stackoverflow.com/questions/24002819/difference-between-and == operator checks if their ...