Thursday 27 October 2016

Functions In Swift3.0

Today we learn about functions used in swift. Functions are self-contained chunks of code that perform a specific task.Swift functions contain parameter type and its return types.

Function Definition

In Swift, a function is defined by the "
func" keyword. When a function is newly defined, it may take one or several values as input 'parameters' to the function and it will process the functions in the main body and pass back the values to the functions as output 'return types'.

Syntax
func funcName (Parameters) -> returntype {
    //Statements
   return parameters
} 


1) Function without  parameter and without return type
func learnSwift(){
  print("Hello Swift")

}

Explation:
 This function having no arguments and return type. func is keyword used before a function name.
"learnSwift" is the function name.

How to call function in Swift: 

Now open your xcode and create a new playground file. After function declaration  now its time to call your function.


2) Function with parameter and having no return type:
3) Function with multiple parameters and  having no return type :
4) Function with paramter and  having  return type:
Here learnSwift function having  String return type. myCurrentVersion is returned as String datatype.


Default Parameter Values :















Here "version" parameter is declared as default parameter value with "3.0"

Variadic Parameters
A variadic parameter accepts zero or more values of a specified type. You use a variadic parameter to specify that the parameter can be passed a varying number of input values when the function is called. Write variadic parameters by inserting three period characters (...) after the parameter’s type name.

The values passed to a variadic parameter are made available within the function’s body as an array of the appropriate type. For example, a variadic parameter with a name of numbers and a type of Double... is made available within the function’s body as a constant array called numbers of type [Double].

















Note*
A function may have at most one variadic parameter.

In-Out Parameters :
Function parameters are constant by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can’t change the value of a parameter by mistake. If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.
You write an in-out parameter by placing the inout keyword right before a parameter’s type.


Note* In-out parameters cannot have default values, and variadic parameters cannot be marked as inout.



















To modify the function parameters we can use  in-out parameter .

Conclusion:
All code in this post was tested against a playground in Xcode 8.
Today we learn about functions used in swift language.Since functions are so important to programming, they definitely need a lot of flexibility to do their job well.
I hope you found this article helpful. If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps. Of course, if you have any questions, don’t hesitate to contact me .Please add your comments to make blog more informative.

Thanks!

Tuesday 25 October 2016

Guard Statement In Swift3

Swift 2 introduces the guard statement. It was designed specifically for exiting a method or function early. The guard statement is ideal for getting rid of deeply nested conditionals whose sole purpose is validating a set of requirements. Take a look at the updated example in which I’ve replaced every if statement with the new guard statement.

Note*

guard statement always has an else clause. The else clause is executed if the condition of the guard statement evaluates to false. Using guard makes much more sense when you’re validating requirements.

Syntax:







Example: 










Output : It will print "fail" because we are passing nil in the function argument.

Now we are passing 56 in the function argument.












 Optional Binding   Vs  guard

Lets take same example with optional binding















Optional binding gives the same output as we have seen in above example with guard statement.

Problem with Optional Binding

There is a problem with this, but you could imagine how confusing it could become if it was nested with numerous conditions that all needed to be met before running your statements.

Why guard is better ?

1) Here we are checking for the condition you do want, not the one you don’t. This again is similar to an assert. If the condition is not met, guard‘s else statement is run, which breaks out of the function.

2) If the condition passes, the optional variable here is automatically unwrapped for you within the scope that the guard statement. This is an important feature that really makes the guard statement useful.

3) With the help of guard statement we can check for bad cases early, making your function more readable and easier to maintain.


Local Notification in iOS10.0


Today, we will learn about how to implement local notifications in iOS 10.Let's do it.

Create a Single View Application. After that place a UIButton on view controller
.
2) Now we create a function for asking the notification permission.

  • Add UserNotifications framework and import in appdelegate class
  • Add UNUserNotificationCenterDelegate.
  • Open your AppDelegate.swift and add your code in didFinishLaunchingWithOptions launchOptions method



Here we call requestAuthorization method of the notification center to ask the user’s permission for using notification. We also request the ability to display alerts and play sounds.

Note*
Don't forgot to call its delegate method.
3) Now add its  delegate method  in  AppDelegate.swift


 @available(iOS 10.0, *)
  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {                     completionHandler(.alert)
    

  }


4) Create action of UIButton named "addLocalNotificationClicked" add notification code inside this button action.
@IBAction func buttonTapped() {
let content = UNMutableNotificationContent()
content.title = "Title"
content.subtitle = "subtitle"
content.body = "Body"
content.categoryIdentifier = "category"                      
let trigger = UNTimeIntervalNotificationTrigger(
timeInterval: 3.0,
repeats: false)
let request = UNNotificationRequest(
identifier: "identifier",
content: content,
trigger: trigger
)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

}

5) Now run your code

























6) You will see  notification  alert asking for permission during app launch.After allowing the notification.You press the  addLocalNotifcation button. Notification appears on the top when app is running on foreground as well as background.


Monday 24 October 2016

Conditional Statements In Swift3.0



Swift provides two ways to add conditional branches to your code: the if statement and the switch statement. Typically, you use the if statement to evaluate simple conditions with only a few possible outcomes. The switch statement is better suited to more complex conditions with multiple possible permutations and is useful in situations where pattern matching can help select an appropriate code branch to execute.

1) If:  It executes a set of statements only if that condition is true.














The if statement can provide an alternative set of statements, known as an else clause, for situations when the if condition is false. These statements are indicated by the else keyword.











You can chain multiple if statements together to consider additional clauses.














Switch: A switch statement considers a value and compares it against several possible matching patterns. It then executes an appropriate block of code, based on the first pattern that matches successfully. A switch statement provides an alternative to the if statement for responding to multiple potential states.
  • switch value {
  • 
    
  • case value 1:
  • 
    
  •     Statements
  • case value 2,  
  •        value 3:
  •       Statement for case 2 and 3
  • default:
  •     otherwise, Execute Default Case
  • }















Interval Matching : Above example solved by interval matching.Each case compares that value to a number or interval. Because the value of approximateCount falls between 18 and 40.So its output is "Easy to find soul mate for you".


Compound Switch Case: To make a switch with a single case that matches both "z" and "Z", combine the two values into a compound case, separating the values with commas.

















Tuples With Switch Case :
You can use tuples to test multiple values in the same switch statement. Each element of the tuple can be tested against a different value or interval of values. Alternatively, use the underscore character (_), also known as the wildcard pattern, to match any possible value.
























Where In Switch Case:
The where statement may be used within a switch case match to add additional criteria required for a positive match. The following switch statement, for example, checks not only for the range in which a value falls, but also whether the number is odd or even:


















Control Transfer Statements:
Control transfer statements change the order in which your code is executed, by transferring control from one piece of code to another. Swift has five control transfer statements:
  • continue
  • break
  • fallthrough
  • return
  • throw

continueThe continue statement skips some statements inside the loop.



break
The break statement ends execution of an entire control flow statement immediately. The break statement can be used inside a switch statement or loop statement when you want to terminate the execution of the switch or loop statement earlier than would otherwise be the case.



fallthrough :
Switch statements in Swift don’t fall through the bottom of each case and into the next one. Instead, the entire switch statement completes its execution as soon as the first matching case is completed. By contrast, C requires you to insert an explicit break statement at the end of every switch case to prevent fallthrough. Avoiding default fallthrough means that Swift switch statements are much more concise and predictable than their counterparts in C, and thus they avoid executing multiple switch cases by mistake.


















Note*
The fallthrough keyword does not check the case conditions for the switch case that it causes execution to fall into. The fallthrough keyword simply causes code execution to move directly to the statements inside the next case (or default case) block, as in C’s standard switch statement behavior.

return:
The return instruction is used either to return a function value or to terminate the execution of a function.






Here we return language name from a function named "studyWhichLanguage".


throw:
 throw is used in error handling.concept of throw is covered in my upcoming  error handling blog.







Wednesday 12 October 2016

Loops in Swift3.0

Swift provides  two types of  for loops.
1) for - in loop
2) for  loop

for - in 















Note*
Swift3.0 remove old C style looping. 

















 for loop  in swift 3.0 













While Loop 
A while loop performs a set of statements until a condition becomes false. These kinds of loops are best used when the number of iterations is not known before the first iteration begins. Swift provides two kinds of while loops:

1)while evaluates its condition at the start of each pass through the loop.

2)repeat-while evaluates its condition at the end of each pass through the loop.

while loop

 syntax

 while (condition) {
   // statements
}















Repeat-While Loop
It will execute at least once before checking the condition. Apple chooses to call it repeat-while instead of do-while for making the working of the loop more consistent with it’s name.
Syntax
repeat {
// statements
}while condition

NOTE*
The repeat-while loop in Swift is analogous to a do-while loop in other languages.














Collection Types in Swift 3.0

Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.
Note*
Swift’s array, set, and dictionary types are implemented as generic collections.

let vs var: 
let:  You can make variable immutable using let keyword.
Note*
It is good practice to create immutable collections in all cases where the collection does not need to change.
var: If you want  to make your variables mutable then you should use var keyword

Collection Types:

  • Array
  • Dictionary
  • Sets
Use the Boolean isEmpty property as a shortcut for checking whether the count property is equal to 0.We can use  isEmpty property with Arrays , Set , Dictionary. 

Array : Arrays are ordered set of collections of values.
Syntax:
To explicitly declare the type of an empty array, wrap the type within square brackets [ ]. You can use either type annotation to set it equal to empty square brackets, or the initializer syntax that uses a parenthesis following the array type:


let arrayItems:[Type] = []      //type annotation.

let arrayItems = [Type]()       // Intializer

 Array with a Default Value:
Swift’s Array type also provides an initializer for creating an array of a certain size with all of its values set to the same default value. You pass this initializer a default value of the appropriate type (called repeating): and the number of times that value is repeated in the new array (called count):

  1. var arrayItems = Array(repeating: 0.0, count: 3)
  2. Output : [0.0 , 0.0, 0.0]
  3. Adding Two Arrays Together:
let firstArray:[Int]  = [1,2,3,4]

let secondArray:[Int] = [5,6,7,8]

let result = firstArray + secondArray

Output: [1, 2, 3, 4, 5, 6, 7, 8]

Subscripting In Array: 

let firstElement = firstArray[0]

Output : 1 

firstArray[1]  = 5      // Error due to let keyword.You can append item to immutable array. Here firstArray is immutable because we are using  let keyword .  

Methods Perform On Arrays
.append()       
.removeLast()  
.popLast()
.reverse()

var firstArray = [1,2,3,4]

append()

arrayItems.append(4)                  // append() is used for adding items in array

removeLast() :Removes and returns the last element of the collection. The collection must not be empty.
firstArray = [1]
firstArray.removeLast()
print(firstArray)                   Output:  []

popLast()Removes and returns the last element of the array.if the array is empty then return nil.

firstArray.popLast() 

print(firstArray)                   Output: [1,2,3,4]

.reverse(): This  method returns a copy of the array with the elements in reverse order. It does not implicitly mutate the array it is called on.

firstArray.reverse()              Output : [4,3,2,1]

ARRAY PROPERTIEs
.first
.last
.count

firstArray.first                               // Return the first element in the array

firstArray.last                               // Return the last element in the array

firstArray.count                           // Return the count of  array


Iteration In Array
for-in  Loop

for item in firstArray {
  print(item)
  
}

SetsA set stores distinct values of the same type in a collection with no defined ordering. You can use a set instead of an array when the order of items is not important, or when you need to ensure that an item only appears once.
Syntax:
The type of a Swift set is written as Set<Element>, where Element is the type that the set is allowed to store. Unlike arrays, sets do not have an equivalent shorthand form.
   
var words = Set<Character>()        //Empty Set 

words = ["a","k","s"]

print(words)                                Output : ["k", "s", "a"]   

 // print in anyorder because set is  unordered collection of unique values


Methods Perform On Sets
.insert()
.remove()
.removeAll()
.removeFirst()


Iteration :

for char in words {
print(char)
}

Set Operations:

















Dictionary:
The type of a Swift dictionary is written in full as Dictionary<Key, Value>, where Key is the type of value that can be used as a dictionary key, and Value is the type of value that the dictionary stores for those keys.
NOTE*
A dictionary Key type must conform to the Hashable protocol, like a set’s value type.
var userDictionary = [String: String]()

var flightsDict: [String: String] = ["US": "Newyork", "AUS": "Australia"]

Use the Boolean isEmpty property as a shortcut for checking whether the count property is equal to 0:

if userDictionary.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The airports dictionary is not empty.")
}

READING A DICTIONARY

Similar to arrays, dictionaries can be subscripted with a key. This syntax returns an optional that will contain nil if the dictionary holds no value for the requested key:

   if let name =  flightDict["name"] {
    print("name ->"\(name))
}

WRITING TO A DICTIONARY

To alter a dictionary by adding a new key-value pair, or overwriting the value of an existing key, the dictionary must be mutable, meaning that it must have been created using var:

var dict: [String: String] = [
"name ": "Rony",
"age" : "27",
"dob" : "08-11-1989"
]

REMOVING FROM A DICTIONARY

dict["name"] = nil

Iteration :

for airportCode in flightsDict.keys {
print("code \(airportCode)")
}

Properties
  • isEmpty
  • count