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")



0 comments:

Post a Comment

Search This Blog

Powered by Blogger.

Blog Archive