Wednesday, 14 June 2017

The guard statement is a Swift language feature introduced as part of Swift 2. A guard statement contains a Boolean expression which must evaluate to true in order for the code located after the guard statement to be executed. The guard statement must include an else clause to be executed in the event that the expression evaluates to false. The code in the else clause must contain a statement to exit the current code flow (i.e. a return, break, continue or throw statement). Alternatively the else block may call any other function or method that does not itself return.Syntax:func function_name (paramsname: paramType…) -> <ReturnType>{guard <boolean expressions> , <condition check> else {// code to be executed if expression is false<exit statement here>} // code here is executed if expression is true}Limitations:*This statement used inside the functions*This occupies the complete method and to do the check and process.Code Snippet:var value:String! = "Tessa"print(value)testFun(v:value)func testFun(v: String?) { guard let vu = v, vu == nil else { print ("Value is nil") return } print("Value is not nil") // Output}Without Guard Statement: #Rust Coding:

funcnonguardSubmit(){ifletname=nameField.text{ifletaddress=addressField.text{ifletphone=phoneField.text{sendToServer(name,address:address,phone:phone)}else{show("no phone to submit")}}else{show("no address to submit")}}else{show("no name to submit")}}

With Guard Statement:

funcsubmit(){guardletname=nameField.textelse{show("No name to submit")return}guardletaddress=addressField.textelse{show("No address to submit")return}guardletphone=phoneField.textelse{show("No phone to submit")return}sendToServer(name,address:address,phone:phone)}funcsendToServer(name:String,address:String,phone:String){...}

functappedSubmitButton(){guardletname=nameField.textwhereisValid(name)else{show("name failed validation")return}sendToServer(name)}funcisValid(name:String)->Bool{// check the name is between 4 and 16 charactersif!(4...16~=name.characters.count){returnfalse}// check that name doesn't contain whitespace or newline charactersletrange=name.rangeOfCharacterFromSet(.whitespaceAndNewlineCharacterSet())ifletrange=rangewhererange.startIndex!=range.endIndex{returnfalse}returntrue}

Sunday, 11 June 2017

What is optional? When declaring variables in Swift, they are designated as non-optional by default. In other words, you have to assign a non-nil value to the variable. If you try to set a nil value to a non-optional, the compiler will say, “hey you can’t set a nil value!”.

var message: String = "Swift is awesome!" // OK

message = nil // compile-time error

An optional declaration doesn’t say “this is an String, which is optional”. It says, “this is an Optional, which may or may not hold an String”

Have you ever struggled with the various “?” and “!” symbols here and there in a Swift code? Or ever found yourself confused about the phrases like

“Forced unwrapping”,

“Optional unwrapping” or “Optional binding”,

“Automatic unwrapping” or “Implicit unwrapping”,

“Nil coalescing”,

“Implicit binding” or “Optional chaining” (will see this later point of time)

You’re in the right place!

Optionals are a powerful feature in Swift language which come to solve the problem of non-existing values. Coming from Java and being passed through the hell of NPEs (Null Pointer Exception), I’m truly excited with this feature of Swift.

Forced Unwrapping:

We use this way in order to get the value of age we put an exclamation mark at the end of the variable.

var age: Int?

age = 23

print(age!) // outputs 23

This option is not a safe one because if age were a nil, it would crash the app, so we need to use a safest way to unwrap the optional Int value.

Optional unwrapping / Binding:

So this is the safest and preferred way to unwrap an optional, we say if age variable really contains a Int value meaning it is not a nil value then unwrap and assign it to myAge variable and that by the way myAge variable will hold an Int type and not an Int? type thus we can use it as it were a normal variable.

But if age contains a nil value then the execution flow won’t get to the if body which is great since we wouldn’t want to use nil.

var age: Int?

age = 23

if let myAge = age {

print(myAge) // outputs 23

}

Automatic / Implicit unwrapping:

It is rare to use this way of unwrapping an optional but it is good to know when you encounter some code using it so it is simply putting the exclamation mark at the end of the type declaration, and then whenever we try to get the value of age, Swift will automatically will unwrap the optional for us giving us the value.

var age: Int! // here goes the exclamation mark

age = 23

print(age) // outputs 23

Nil coalescing:

Sometimes we want to use a default value when the optional is nil. Let’s take a look at this example:

let optionalInt: Int? = nil

var result: Int

if optionalInt != nil {

result = optionalInt!

} else {

result = 0

}

print("The result is \(result)") // prints "The result is 0"

This could be reduced to a one line by using a ternary operator (the “?” below represents the ternary operator).

let optionalInt: Int? = nil

let result = optionalInt != nil ? optionalInt! : 0

print("The result is \(result)") // prints "The result is 0"

Nil coalescing allows us to shorten this even more, this just means (??) “If optionalInt is nil then use zero, otherwise use its unwrapped value”.

Sunday, 4 June 2017

A tuple in Swift is a construct that groups multiple values together into a single compound value. Tuples can be useful when more than one value type can provide more useful information about the outcome of a behavior or action than simply returning a single value. They are meant to be temporary and are not suited for more complex data structures that will probably persist beyond a temporary scope

var person = ("Sachin", "Ramesh")

Named elements:
You can name the elements from a tuple and use those names to refer to them. An element name is an identifier followed by a colon(:).

Functions and Tuples:
Tuples can also be useful as a return type for a function to return multiple values as part of a single compound value. Continuing with our code example, let's build out the function that's responsible for returning this tuple.