Tuesday, 24 December 2019

Swift Short Notes : Swift Chapter 1

swift is a scripting language  (Scripting language same as programming language only diff is it does not have clear compilation steps. max scripting languages are interpreted at run time  )
Swift for iOS, tvOS, watch OS , OSX and servers too.

Swift is safe (type checking etc at compile time, strict type check), fast (static language), interactive (as script language) and open source language.
Obj-C can be used in swift.

Compile time error:1.overflow , underflow with arithmetic operator 2.addition of
different type (eg int and float) etc.
Most of framework in swift or wrapper provided interfaces in swift.

Apple provides most of system interfaces(which allows to access the lower levels)

called as framework.Framework is directory structure contains .h, resources( such
as storyboard, image files, localized strings etc.) , dynamic shared lib etc files.

iOS Architecture

foundation framework :contains data types, collection, connection , max service that needed to interact with lower level
Cocoa framework :contains Foundation andAppKit frameworks,
Cocoa touch  framework :contains  Foundation and UIKit frameworks)framework. [Appkit is OSX ui framework and UIKit is iOS ui framework.]

Sunday, 22 December 2019

Swift Short Notes : Swift Chapter 2

let for constants and var for variable
Data type of container is inferred by compiler based on first assign value.
We can also specify the data type for container called type annotation.(let text:String).


Naming to container:- naming will not contain whitespace, mathematical symbol , arrows, line- and box drawing characters and private use unicode points. Apart from anything including unicode.(ex: let 🐶 🐮 = "dogcow”)
You can use the reserved keyword with back ticks surrounded.(var `class`:String ="AP History")

print(_:separator:terminator:) to print value. terminator is default newline (can provide required). separator is separator for multiple string send to print. Use around parenthesis to print const/var and with backslash when const/var
inside string.

comments: same c with multiline(/*….*/) nested.

Basic types are structure and Structure is almost like class.

 when to use struct(value types - on stack) over class(reference type - on heap)
when struct small and copiable (pass by value, if small save memory) , as pass by value no worry of changing
value(even in case of multithreaded environment). 
struct memory can be on stack so life about that block only.

Classes prefered in below cases
1.copying and comparison not needed.
2.lifetime of instance mostly on heap.

As a general guideline, consider creating a structure :
• The structure’s primary purpose is to encapsulate a few relatively
simple data values.
• encapsulated values will be copied rather than referenced when you assign or pass around an instance of that structure.
• The structure does not need to inherit properties or behavior from
another existing type.

In all other cases, define a class, and create instances of that class to be managed and passed by reference. In practice, this means that most custom data constructs should be classes, not structures.


Data types:
Integer: signed and unsigned 8,16,32 and 64 (ex.UInt8, Int32). (Binary with 0b , octal with 0o and hex with 0x prefixes)
Floating: float 32 bit (precision 6 digit), double 64 bit (Precision 15 digit). (Double is default type for type infer) .Only decimal and hexadecimal.
Booleans: Bool with values true/false.
Tuples: new data type to return multiple values(its like struct without declaration) .
Group multiple values of any type. ex:Ex. let http404Error = (404, "Not Found") and accessed with .index of param in tuple.
Decode can be :let (statusCode, statusMessage) = http404Error OR let (justTheStatusCode, _) = http404Error OR http404Error.0 , http404Error.1 OR Ex. let http200Status = (statusCode: 200, description: "OK") access like http200Status.statusCode and http200Status.description
Optionals: its used where can have value and can not have value(nil). ex: let convertedNum:Int? = Int(“123”) here is optional Int or Int? .default value is nil. We can use optionals with basic data type also.(Data types are structures).
nil: u can set nil to optional variables for valueless state. setting nil to non optional is error.
To access the optional value need to use exclamation mark (!). If u used ! to access value which does not have value it triggers runtime error.
Void in swift is empty tuple(tuple with zero elements.) can be written as ().

String , Int , Double and Bool are hashable (Hashable is protocol provide hash integer value.a == b, then a.hashValue == b.hashValue )



Implicitly unwrapped optionals: when sure optional always has value, use ! instead of ? and no need to unwrap to access value directly accessed. (If it has nil and tried to access then runtime error.)
Ex:
let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString //accessed directly without exclamaition


Optional Binding: Its used to find out whether optional contains value and if has value assign to temp variable or constant.ex:
if let constantName = someOptional {
statements
}
even can check nil or not
if someOptional == nil
{
}


For readability u can add _ . ex: 1_000 i.e.(1k).

Explicit conversion: with ctor of that type.i.e To use explicit conversion use
Datatype(value_to_convert).
ex let x:Int8
let y = Int32(x)

Number literal does not have data type so below is not error.
let test= 3 + 0.05

typealias is like typedef. 
ex: typealias AudioSample = UInt16


Error/Exception Handling: like java function need to declare with throws keyword at end.
ex:
func canThrowError() throws ->return_type // throws should be after parenthesis
and before return type
{
//here throws is keyword
}
do
{
try canThrowerror()
}
catch
{
}
There can be multiple catch blocks with different data types like Java.


Assertions: It is runtime check that boolean should have true value , for false it terminate app. Its disabled when compiled with optimization like release config.
Used also for debug message in case of assertion.
Ex: let age = -3
assert(age >= 0, "A person's age cannot be less than zero")



Saturday, 21 December 2019

Swift Short Notes : Swift Chapter 3 Operator


Basic operator: almost all c operator with detecting overflow underflow errors.


If want to use overflow underflow then us overflow operator i.e & with that operatorEx:
a &+ b

% (Modulus  operator)  can be used on floating point . remainder always took sign of first number.

Range operator: 
1)Closed range operator : a…b i.e start from a to equal to b 
2)Half open range operator: a..<b start from a and less than b (equal to b-1).

unLike c assignment operator does not return value. (In C a=10 then return value is 10 in swift only assignment)

Support shorthand i.e += , -= etc.

Comparison operator same like c with extra === and !== . These two operator is used to test for two object reference refer to same object instances.

Tuples with less than seven elements can be compared , comparison is from left to right.

Nil coalescing operator: (a ?? b) : this unwraps an optional “a” if it contains a value or returns default value “b” if “a” is nil. b is same of a’s data type.

Logical operator(&& , || , !) is same with same optimisation like c.

Friday, 20 December 2019

Swift Short Notes : Swift Chapter 4 String


String and Character are data type. Mutability with var Keyword. Strings are value type(not object or ref kind). (Value types mean type of structure or basic type , object/ref kind means type of class object/ref)

Every string is composed of encoding-independent Unicode characters and provides support for accessing those characters in various Unicode representations.

Swift String class is bridged with NSString. all function of NSString available when typecast to NSString.

When you pass string value to function then each case new copy of existing string value is created and new copy is passed or assigned. Becoz String is value type not reference type.
Swift’s compiler optimizes string usage so that actual copying takes place only when absolutely necessary.

Its valid: let exclamationMark: Character = "!" // string to character.

Obj-C Stringwithformat like : let message = "\(multiplier) times 2.5 is \ (Double(multiplier) * 2.5)”

Get character from string with characters property becoz they can not access directly as its encoding independent unicode characters.

Unicode scalar is unique 21 bit character and swift’s native string type is built from unicode scalar values.
usage of same :
let eAcute: Character = "\u{E9} // é
let combinedEAcute: Character = "\u{65}\u{301}" // e followed by ́ (This is called extended grapheme cluster as combination of multiple character in one)

As seen two different way for same character but character count for both is same i,e. one. But actual amount of memory required is different.

The count of the characters returned by the characters property is not always the same as the length property of an NSString that contains the same characters.
The length of an NSString is based on the number of 16-bit code units within the string’s UTF-16 representation and not the number of Unicode extended grapheme clusters within the string.”
Accessing string with . startIndex, endIndex, predecessor, sucessor , advancedBy methods.
let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// G
greeting[greeting.endIndex.predecessor()]
// !
greeting[greeting.startIndex.successor()]
// u
let index = greeting.startIndex.advancedBy(7)
greeting[index]s
// a
Compare string with == and != operators.
When unicode string written to file then it gets converted to either Utf8 or utf16 or utf32 bit.

Thursday, 19 December 2019

Swift Short Notes : Swift Chapter 5 Collections


Collection Types are structs not classes.
Same like objC Array (Ordered collection of values), Set (unordered collection of unique values) and Dictionary(Key- value mapping).

Swift collection type implemented as generic collection(template) and they are bridged to objC foundation’s NSArray. (Bridging is done with as keyword).

Array
Some Ex:
var someInts = [Int]()
let arraInt :Array<Int>
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
shoppingList[4...6] = ["Bananas", "Apples"]
for item in shoppingList {
print(item)
}
for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}

Set: Storing type must be hashable .(Hashable needs to conform to Hashable protocol. Hashable consforms to equatable so == needs to be implemented.). Set has set property like intersect, subset, union etc
Some Ex
var letters = Set<Character>()
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]


for genre in favoriteGenres {
print("\(genre)") 
}



Dictionary :(Key must be hashable)
Some Ex:
var namesOfIntegers = [Int: String]()
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}
for airportName in airports.values {
print("Airport name: \(airportName)")
}
Items in Dictionary may not be iterated in same order in which they inserted.

Swift Short Notes : Swift Chapter 6 - Control flow


1.for loop
for index in 1...5 // Here index is constant and value set with each iteration
{
print("\(index) times 5 is \(index * 5)")
}
for _ in 1…10
{
print(“print”)
}

2.while loop
while condition
{
statements
}
repeat //like do while
{
statements
} while condition

3.if and if-else
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
}
else {
print("It's not that cold. Wear a t-shirt.")
}

4.switch
break keyword not required. support more data type. multiple switch
cases can have same value but first matching is executed. each case have atleast
one statement otherwise its error(use break for empty cases).
switch some value to consider {
case value 1:
respond to value 1
case value 2, value 3:
respond to value 2 or 3
case half open or closed range: // 1..<5 10…1000
respond to range
case tuple //tuple can contain wildcard character. ( _ ,0 ) means first element can be
anything.
respond to tuple
default:
otherwise, do something else
}


half open or closed range returns either intervaltype or a range.

Value binding in switch where clause in switch to check for additional conditions.
switch case can bind/assign the value to temp const/value.
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0): // first value can be anything second should be 0
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y) where x==y:
print("somewhere else at (\(x), \(y))")
case let (x, y) where x== (-y):
print("somewhere else at (\(x), \(y))")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}



Control transfer protocol: 
continue , break , return , fallthrough, throw.
continue : skip current iteration
break: ends execution of loop
fallthrough: behavior like c in switch if not break then go to next case use .fallthrough as swift break behavior is default.
return: get out of function
throw: to raise exception

Labeled Statement
like c , used to break or continue.
label name: while condition
{
statements
}


guard: guard statement is like if statement , executes statement based on boolean value of expression.
guard let location = person["location"] else {
print("I hope the weather is nice near you.")
return
}
You can think of guard more like an Assert, but rather than crashing, you can
gracefully exit. with guard fail case else clause must transfer control to exit the code block in
which the guard statement appears.
guard is used mostly better readability than if.

Checking API Availability
if #available(iOS 9, OSX 10.10, *) { //*, is required and specifies that on any other platform any other platform . min os version
// Use iOS 9 APIs on iOS, and use OS X v10.10 APIs on OS X
} else {
// Fall back to earlier iOS and OS X APIs
}

Wednesday, 18 December 2019

Swift Short Notes : Swift Chapter 7 - Functions


swift function can be nested.
Syntax:
func function_Name ( argu1:DataType , argu2:DataType …) -> return_Type
{
}
For multiple written values use tuple.
Ex: func minMax(array: [Int]) -> (min: Int, max: Int)
{
return (currentMin, currentMax)
}
return type can be optional tuple means it can or can not have values.(with ? in end .i.e. (Int, Int)?).
local parameter name used when declaring/defining function (local name must be unique)and external parameter name is used when calling function (external name can not be unique). If want to omit external parameter name for second and subsequent then use _ instead of external name.

When calling function By default first parameter omits its external name and second subsequent parameters use their local name as external name.
func someFunction(externalParameterName localParameterName: Int)
{
// function body goes here, and can use localParameterName
}
if you provide an external parameter name for a parameter, that external name must always be used when you call the function.


Ex:
func sayHello(to person: String, and anotherPerson: String) -> String {
return "Hello \(person) and \(anotherPerson)!"
}
print(sayHello(to: "Bill", and: "Ted"))

Default parameter name like c++
func someFunction(parameterWithDefault: Int = 12) {}

Variadic Parameters ellipse ( … ). Zero or more value of specific type.
Ex:
func arithmeticMean(numbers: Double...) -> Double {
for number in numbers {
}}

In-Out Parameter:
Default function param are constant. Use inout when want to change value of param passed to function.Use & when passing variable.
In-out parameters cannot have default values, and variadic parameters cannot be marked as inout.

Ex: func swapTwoInts(inout a: Int, inout _ b: Int) ;// place of inout changed in swift 4
func swapTwoInts(a: inout Int, _ b: inout Int)

function type (function pointer ) like in c .can be passed as argument to another function.
func addTwoInts(a: Int, _ b: Int) -> Int {}
var mathFunction: (Int, Int) -> Int = addTwoInts

Nested Functions: function inside function. Its not directly accessible. An enclosing function can also return one of its nested functions to allow the nested function to be used in another scope.

x

Tuesday, 17 December 2019

Swift Short Notes : Swift Chapter 8 - Closures


Closures
Similar to blocks in ObjC.
{ (parameters) -> return type in
statements
}
Ex:
reversed = names.sort(
{ (s1: String, s2: String) -> Bool in
return s1 > s2
}
)

Inferring Type From Context

ex: reversed = names.sort( { s1, s2 in return s1 > s2 } )
here parameter type and return type is inferred .

Shorthand Argument Names
swift automatically provides shorthand argument names to inline closures, argument by $0, $1 , $2 ..so on.
reversed = names.sort( { $0 > $1 } )

Operator Functions
above can be written as shorter like
reversed = names.sort(>)
so above (>) operator is a function (overloaded operator.)

Trailing Closures
Its mostly used when want to pass closure as final argument and closure expression is long. that is written outside of and after the parenthesis of function call.
someFunctionThatTakesAClosure() {
// trailing closure's body goes here
}
reversed = names.sort() { $0 > $1 }
if closure is the only parameter to method with trailing closure no need to write parenthesis.
reversed = names.sort { $0 > $1 }

Capturing Values
closure capture the value from the surrounding context in which it is defined.
“As an optimization, Swift may instead capture and store a copy of a value if that value is not mutated by a closure, and if that same value is not mutated after the closure is created.Swift also handles all memory management involved in disposing of variables when they are no longer needed.”
Swift uses capture lists to break these strong reference cycles, If closure is property of object.
functions and closures are reference types
If a closure is passed as an argument to a function and it is invoked after the function returns, the closure is escaping.
A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns (means the closure is called after function completes).. you can write @noescape before the parameter name to indicate that the closure is not allowed to escape.
ex:
func someFunctionWithNonescapingClosure(@noescape 

closure: () -> Void) {
closure()
}
swift 3 nonescape keyword is removed and its default behaviour in swift 3
@noescape means after function (to which closure passed as parameter) completes it is not allow to call closure. OR destroy closure reference after function completes.

Its compile time error if you make esacpe closure as nonescape which is capturing variable or constant.
Ex: below u can not make nonescape because it will capture array
completionHandlers and closure will get called on completion callback so its should escape.
var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: () -> Void) {
completionHandlers.append(completionHandler)
}

Autoclosures
its a closure that is automatically created to wrap an expression that is passed as argument to function.
It does not take any argument but it can return value of expression.
Ex:
// customersInLine is ["Alex", "Ewa", "Barry", "Daniella"]
func serveCustomer(customerProvider: () -> String) {
print("Now serving \(customerProvider())!")
}
serveCustomer( { customersInLine.removeAtIndex(0) } )
// Prints "Now serving Alex!
this can be converted to autoclosure like:
// customersInLine is ["Ewa", "Barry", "Daniella"]
func serveCustomer(@autoclosure customerProvider: () -> String) {
print("Now serving \(customerProvider())!")
}
serveCustomer(customersInLine.removeAtIndex(0))
// Prints "Now serving Ewa!



Monday, 16 December 2019

Swift Short Notes : Swift Chapter 9 - Enumerations


Enumerations
enum group of related values. same like c. not required to provide value to each of enum. Value can be string , character, float , int type. If u want u can specify the literal values of any kind. (for class object values need to use protocols Equatable, RawRepresentable )
Ex:
enum CompassPoint {
case North
case South
case East
case West
}
Each enumeration definition defines a brand new type.
Enum type name should start with capital letter.
Associated Values ( Mainly used to keep the two or more different kind of data types in one)

Ex Inventory system need to track product with two different types of barcode 1.with 1D barcodes 2. with 2D barcodes
enum Barcode {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
var productBarcode = Barcode.UPCA(8, 85909, 51226, 3)
productBarcode = .QRCode("ABCDEFGHIJKLMNOP")
same variable can contain any kind of barcode . but container of variable and constant store one type of value at time i.e either UPCA or QRCode in above case.  Not both at a time.

Usage in switch case
switch productBarcode {
case .UPCA(let numberSystem, let manufacturer, let product, let check):
print("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case .QRCode(let productCode):
print("QR code: \(productCode).")
}

Raw Values
Called as default values. i.e. value assigned to cases. Each raw value must be unique within its enumeration declaration.
ex:
enum ASCIIControlCharacter: Character {
case Tab = "\t"
case LineFeed = "\n"
case CarriageReturn = "\r"
}
When strings are used for raw values, the implicit value ( value assigned automatically like c if 0 assigned to first then 1, 2, next onwards) for each case is the text of that case’s name.
If you define an enumeration with a raw-value type, the enumeration automatically receives an initializer that takes a value of the raw value’s type (as a parameter called rawValue) and returns either an enumeration case or nil. You can use this
initializer to try to create a new instance of the enumeration.
This example identifies Uranus from its raw value of 7:
let possiblePlanet = Planet(rawValue: 7)

Recursive Enumerations
In this case an enumeration has another instance of the enumeration as  associated value.
To indicate enumeration is recursive use indirect keyword before it which tell compiler to insert necessary layer of indirection.
Ex:
enum ArithmeticExpression {
case Number(Int)
indirect case Addition(ArithmeticExpression, ArithmeticExpression)
indirect case Multiplication(ArithmeticExpression, ArithmeticExpression)
}
to enable all the enumeration cases as indirect write indirect before enumeration.
indirect enum ArithmeticExpression {
case Number(Int)
case Addition(ArithmeticExpression, ArithmeticExpression)
case Multiplication(ArithmeticExpression, ArithmeticExpression)
}

This enumeration can store a plain number, the addition of two expressions, and the multiplication of two expressions.
func evaluate(expression: ArithmeticExpression) -> Int {
switch expression {
case let .Number(value):
return value
case let .Addition(left, right):
return evaluate(left) + evaluate(right)
case let .Multiplication(left, right):
return evaluate(left) * evaluate(right)
}
}


Search This Blog

Powered by Blogger.

Blog Archive

Swift Short Notes : Swift Chapter 1

swift is a scripting language  (Scripting language same as programming language only diff is it does not have clear compilation steps. max...