Static and Class Keyword in Swift

Before we talk about how static and class keyword are different with each other, lets see how they are similar.

How They Are Similar?

Static and Class keyword when applied on a variable or function, make it Type method.

Type Methods are the methods which you can call directly without creating instance of the class. Whereas, in Instance Method, we need to create an instance of the class first to access the property. Below is an example which will help you understand better.

class Employee  {
    
    var name = "Keshu"
    class var id : Int {
        return 007
    }
}

print(Employee.id) // Type Method : Accessing id directly on type. Without creating instance.
print(Employee().name) // Instance Method : Creating Instance then accessing name

Difference: Static and Class

STATICCLASS
Can be applied on Stored Property as well as Computed Properties.Can only be applied on Computer Properties.
Static method declaration are allowed in Struct as well as Classes.Class keyword can only be used in Classes.
NOTE: Static properties can not be overridden by inheriting classes.NOTE: Class properties can be overridden by inheriting classes.

static keyword is same like final class. final keyword makes the variable or function final i.e. they can not be overridden by any inheriting class.

class Employee  {
    
    static var name = "Keshu"
    class var id : Int {
        return 007
    }
}

class EmployeeAddress : Employee {
    
    override static var name = "Keshu New Name" // Error : Cannot override with a stored property 'name'
    
    override class var id: Int { // Runs successfully.
        return 100
    }
}

As you can see in above code, the static property can not be overridden by EmployeeAddress class. Whereas the id property has successfully been overridden. This is the major difference between Static and Class Keyword. I hope its clear to you now. If any queries, feel free to ask in comments.

Also, do you know what are Variadic Functions? Variadic Functions in Swift

Variadic Parameters in Swift

Variadic paramaters are those which accept from zero to N number of parameters.

The most common method which you use almost daily is print() method

You can do print(“abc”) or you can also do print(“a”,”b”,”c”,”d”) or any number of paramters and it will print it all.

Lets see how you can create your own function using variadic parameters.

func addition(_ numbers : Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum = sum + number
    }
    return sum
}


let sum = addition(0,1,2,3,4,5,6,7,8,9)
print(sum) // 45

You can see in the above code instead of just saying Int, I have entered Int… i.e. Int with three dots. This is how variadic parameters are declared. Now, numbers will be an array of Int type and you may use for loop to sum the numbers. Or you can also reduce it to below code:

func addition(_ numbers : Int...) -> Int {
    return numbers.reduce(0, +)
}

let sum = addition(0,1,2,3,4,5,6,7,8,9)
print(sum) // 45

Thats It. You now know how to create Variadic Parameters in Swift. Cheers.

Extensions In Swift

It’s been a long time since i have written a blog. But today, a post on Stackoverflow motivated me so much to write a post on use of Extensions In Swift. Why? Because i have seen many beginners totally neglecting extensions and have no idea how useful it can be.

So i will try to list the points here today and discuss on it one by one on what functionalities does Extensions provide us:

  1. You may use Extensions for conforming to a protocol.
  2. Define instance methods and type methods
  3. Provide New Initializers.
  4. Define Subscripts
  5. Define and use new nested types.
  6. Add computed instance properties and computed type properties

NOTE:

Extensions can add new functionalities to a type, But they can not override an existing property.

Now let’s discuss on the above points one by one.

Extension For Conforming to A Protocol

When using a UITableView, we always make our ViewController conform to UITableViewDataSource And UITableViewDelegate protocol methods.

class YouViewController : UIViewController, UITableViewDataSource, UITableViewDelegate { 
    // your viewController setup code
    // your table view callback methods
}

Any if you are using lets say, UICollectionView also in the same controller, your class declaration will looking something like this now:

class YouViewController : UIViewController, UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    // your viewController setup code
    // your table view callback methods
    // your collection view callback methods
}

You see whats happening above? The more and more functionalities you are adding, your class has to conform to the protocols and then you will have to write all the callback methods in same class which makes the code hard to read. Whats the solution? Glad you asked. Extensions.

class YourViewController : UIViewController { 
    // your viewController setup code
}

extension YourViewController : UITableViewDataSource, UITableViewDelegate { 
    // your table view callback methods
}

extension YourViewController : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { 
    // your collection view callback methods
}

This way you can make your code easy to read using Extensions In Swift. If you were not following this pattern till now, I would suggest better start following it.

Extensions on Instance Method or Type Methods

Instance Method are the methods which you call on instance of a type.

For eg: The code below declares a class named ArithmeticOperations and then declares a function inside it named add(), which takes multiple Integers as input and then returns the sum of all the Integers.

NOTE: I have used Variadic Parameters in defining the add function, If you dont know about it, read this post and learn within a minute. Variadic Parameters in Swift

import Foundation

class ArithmeticOperations : NSObject {
    
    // Instance Method
    func add(_ num : Int...) -> Int { // variadic parameter
        return num.reduce(0, +) // adds all the numbers in num array and returns the sum.
    }
    
    // Type Method
    class func printAnything() {
        print("Aabara ka dabara")
    }
}

//creating instance and then calling the method
let sumObj = ArithmeticOperations()
print(sumObj.add(0,1,2,3,4,5,6,7,8,9)) // 45


// calling the type method

ArithmeticOperations.printAnything() // Aabara ka dabara

As you can see above, the instance method can only be called by creating a instance of it first and then calling the function.

Whereas, for calling the type method, we can directly do it without creating an instance.

Now that you have understood what instance method and type method is, Lets come back to how we can use Extensions in it.

class ArithmeticOperations : NSObject {
    func add(_ num : Int...) -> Int {
        return num.reduce(0, +)
    }
    class func printAnything() {
        print("Aabara ka dabara")
    }
}

//MARK: Subtraction
extension ArithmeticOperations {
    func subtract(_ num : Int...) -> Int {
         return num.reduce(0, -)
    }
}

let subtractObj = ArithmeticOperations()
print(subtractObj.subtract(10,9,8,7,6,5,4,3,2,1)) // -55

In the above code, we have created an extension for the same class ArithmeticOperations for and added a Subtraction function in it. And now we can use the subtraction method same as the addition method anywhere in the project.

Extensions come really handy when you have to work on pre-defined methods.

Lets say you want extend Int type and add a function to it which returns the cube of a number.

extension Int {
    func cube() -> Int {
        return self*self*self
    }
}
print(3.cube()) // 27

Easy right?

Add New Initializers Using Extension

Coming Soon.

Subscript – Using Extensions In Swift

Coming Soon.

Nested Types

Coming Soon.

Computed Properties

Coming Soon

Show Push Notifications when app running in the foreground iOS Swift

Push notifications are a nice way to inform your users about the offers, user-specific update or any message that you want to broadcast to all users.

If your app is running, it can be in two states. Either in the background or in the foreground.

Push notifications work well when the app is in the background and you can see the notification banner presented with a sound(if provided) on your iPhone/iPad. But what about when the app is in the foreground?

Apple does not show up push notifications by default when your app is in the foreground state. So what to do? You have to write some code to deal with the situation of your app receiving a notification while it is in the foreground.

If you receive local or remote notifications while your app is running in the foreground, you’re responsible for passing the information to your users in an app-specific way.

Apple

Apple guidelines are clear. You are responsible for handling the push notifications in the foreground state. So how to achieve this? Don’t worry, it’s pretty easy. Below are the steps.

Steps to show Push Notifications in the foreground

Step 1 : Add delegate UNUserNotificationCenterDelegate in AppDelegate class.

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

Step 2: Set the UNUserNotificationCenter delegate in didFinishLaunchingWithOptions

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        UNUserNotificationCenter.current().delegate = self
        return true
    }

Step 3: This step will allow your app to show Push Notification even when your app is in foreground

  
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        print(userInfo) // the payload that is attached to the push notification
        // you can customize the notification presentation options. Below code will show notification banner as well as play a sound. If you want to add a badge too, add .badge in the array.
        completionHandler([.alert,.sound])
    }

Step 4: If you want to perform an action on the click of a push notification, you can do it using the below method

   
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                   didReceive response: UNNotificationResponse,
                                   withCompletionHandler completionHandler: @escaping () -> Void) {
           let userInfo = response.notification.request.content.userInfo
           // Print full message.
           print("tap on on forground app",userInfo)
           completionHandler()
       }
    

Well, that was it! You have successfully configured push notifications to receive it in the foreground state too.

It was EASY, right? Do let me know in the comments.

Also, do not forget to become a subscriber by entering your email below so that you can receive the tutorials directly in your inbox.

Namaste!

Passing Data Between View Controllers in Swift

Passing data from one view controller to another view controller is something you need in almost every app. But yet I have seen many people struggling in this. So I have decided to write this blog for beginner level iOS App Developers to understand how to pass the data.

There could be two scenarios when you are changing the view controllers.

  1. You are moving from ViewController1 to ViewController2
  2. You are coming back from ViewController2 to ViewController1

Also, there could be two ways in which you are moving from ViewController1 to ViewController2.

  1. Using the navigation controller
  2. Using storyboard segues.

Now, we will discuss passing data between the view controllers using the navigation controller and using storyboard segues separately.

Passing data when pushing or presenting View Controller

1. Sending data from ViewController1 to ViewController2

For navigating from VC1 to VC2, we use the “push” method. For coming back from VC2 to VC1, we use the “pop” method. We can also use “present” if we want to present our view controller modally.

Below is the code to move from VC1 to VC2

//1 Instantiating ViewController2 from storyboard
let vc2 = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ViewController2") as! ViewController2

//2 pushing ViewController2 to move to top of the navigation stack
self.navigationController?.pushViewController(vc2, animated: true) 

The above code would take you from VC1 to VC2. But where are we passing data? Relax.

//1  
let vc2 = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ViewController2") as! ViewController

//2
vc2.myName = self.userName
        
//3
self.navigationController?.pushViewController(vc2, animated: true)

So in the above code, you can see #2, here we are assigning self.userName, which is in ViewController1 to vc2.myName. When the View Controller 2 will load, its myName value will be equal to the value of self.userName that we passed.

Easy, Right? similarly, you may also do when presenting your view controller modally.

//1  
let vc2 = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ViewController2") as! ViewController

//2
vc2.myName = self.userName
        
//3
self.present(vc2, animated: true, completion: nil)

You can pass any data type, whether string, array, JSON, etc.

Sending data back from ViewController2 to ViewController1

Sending data forward is easy. While sending data back to the controller can be a bit tricky for beginners.

Data is sent back to the controller with the help of Delegates.

Delegates are a design pattern that allows one object to send messages to another object when a specific event happens.

James Rochabrun

I am writing a separate blog on sending data back to View Controller using Delegates. I will update the link here.

Passing Data using Segues

Segues are another way of transition from one view controller to others and are implemented through a storyboard. I will not cover how to create a segue here as I assume you already know it. If not, here is the link from Apple Documentation

The starting point of a segue must be a view or object with a defined action, such as a control, bar button item, or gesture recognizer. You can also create segues from cell-based views such as tables and collection views.

Apple Docs

Segues can be implemented in two ways:

  1. From a view or object to Next View Controller
  2. From View Controller to Next View Controller

When you do not need to pass any data, you can create an object to Next View Controller segue and implemented it all through a storyboard.

But when you need to pass the data, we need to make sure to create the segue between View Controller to View Controller. There can be multiple segues between view controllers and we use segue identifiers to identify them.

Go ahead and create a segue from ViewController1 to ViewController2 and click on the connecting arrow line to open it in Attribute Inspector in the right panel. Here, assign the identifier to the segue. For example: “nextVCSegue”

Also, create a button in your ViewController1 on click of which we will perform the segue. Declare an @IBAction of that button.

//1 
 @IBAction func submitBtnPressed(_ sender : Any) {
    //2
    performSegue(withIdentifier: "nextVCSegue", sender: self)
 }
  
 //3 prepareForSegue function is called everytime you perform a segue.

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        //4
        if segue.identifier == "nextVCSegue" {
            //5
            if let nextVC = segue.destination as? ViewController2 {
                //6
                nextVC.myName = self.name
            } else {
                print("error")
            }
        }
    }
  1. We created an @IBAction that will execute on the submit button click.
  2. Here we are telling the controller to perform segue using the identifier “nextVCSegue”.
  3. Now when performSegue starts, it will call prepareForSegue function. In this function, we will assign the data that we need to pass to the next view controller.
  4. PrepareForSegue function is called for every segue that is happening from the view controller. But here in our case, we only want to pass the data when the segue is from ViewController1 to ViewController2. And how would we identify it? Yes. Using segue Identifier. So we will check if the segue identifier is “nextVCSegue” or not.
  5. segue has a destination property that you can use to know what your destination view controller is. So here we are assigning out nextVC object to the destination view controller which is ViewController2.
  6. Now we can use nextVC to access all the properties you declared in ViewController2 and assign its value here. So here we are assigning our name variable value to nextVC myName variable.

Done. You have successfully passed your data from ViewController1 to ViewController2.

Subscribe below to receive latest blog updates directly in your inbox and help yourself become a better developer.