Wednesday 14 June 2017

Guard Statement in Swift Programming

Correction: Instead of where replace with , (comma) 

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:
func nonguardSubmit() {
    if let name = nameField.text {
        if let address = addressField.text {
            if let phone = 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:
func submit() {
    guard let name = nameField.text else {
        show("No name to submit")
        return
    }

    guard let address = addressField.text else {
        show("No address to submit")
        return
    }

    guard let phone = phoneField.text else {
        show("No phone to submit")
        return
    }

    sendToServer(name, address: address, phone: phone)
}

func sendToServer(name: String, address: String, phone: String) {
  ...
}
Guard Statement Improvised Code 1:
guard let name = nameField.text where name.characters.count > 3 && name.characters.count <= 16, let range = name.rangeOfCharacterFromSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) where range.startIndex == range.endIndex else {
    show("name failed validation")
    return
}

sendToServer(name)
Guard Statement Improvised Code 2:
func tappedSubmitButton() {
    guard let name = nameField.text where isValid(name) else {
        show("name failed validation")
        return
    }

    sendToServer(name)
}

func isValid(name: String) -> Bool {
    // check the name is between 4 and 16 characters
    if !(4...16 ~= name.characters.count) {
        return false
    }

    // check that name doesn't contain whitespace or newline characters
    let range = name.rangeOfCharacterFromSet(.whitespaceAndNewlineCharacterSet())
    if let range = range where range.startIndex != range.endIndex {
        return false
    }

    return true
}
Courtesy: Link1, Link2

Sunday 11 June 2017

Optionals in Swift Programming




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”.

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

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

Sunday 4 June 2017

Tuples In Swift Programming

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(:).

var person = (firstName: "Sachin", lastName: "Ramesh")

var firstName = person.firstName // Sacin
var lastName = person.lastName // Ramesh

Accessing a Tuple:

let (firstName, lastName) = person
print(firstName) => "Sachin"
print(lastName) => "Ramesh"

let (onlyFirstName, _) = person
print(onlyFirstName)=> "Sachin"

Indexing a Tuple:
let firstName = person.0
let lastName = person.1
print(firstName) => "Sachin"
print(lastName) => "Ramesh"

Accessing it's Named Values:
let person = (firstName: "Sachin", lastName: "Ramesh")
print(person.firstName) => "Sachin"
print(person.lastName) => "Ramesh"

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.

// Function Definition
func getFullName() -> (firstName: String, lastName: String) {
  let person = (firstName: "Sachin", lastName: "Ramesh")     //Assume getting from HTTP.get(url)
  return (person.firstName, person.lastName)
}

// Calling the Function
let person = getFullName()
print(person.firstName) => "Sachin"
print(person.lastName) => "Ramesh"