What is the difference between Self vs self in Swift?

App Developer
5 min readDec 19, 2022

--

This article revolves around self and Self in Swift. Taking a macroscopic overview of self and Self then self(one with lower case) is an instance or property of an instance, it can be object of class or object of structure. On the other hand Self denotes a type.

https://youtu.be/DxIWqB50XPk

Now let’s dive deep into the two. So first of all let’s understand the scenarios wherein self can be used.

(I) When trying to differentiate between local property and the property at the class level or structure level: Consider a scenario wherein the property name and the argument name is same for example:

struct Person{
var name:String
init(name: String){
name = name
}
}

Clearly we can see that in the above init method the argument name and the property name is same which is name, so the compiler would get confused as to which name we are talking about so in order to remove this ambiguity we tend to add a self to the name. Therefore leading to the following piece of code

struct Person{
var name:String
init(name: String){
self.name = name
}
}

(II) With Extension : Use of self can be found again in cases of extension for example consider the following piece of code.

struct Person{
var name:String
init(name: String){
self.name = name
}
func isValidName(){
print(name.isStringValid())
}
}
extension String {
func isStringValid()-> Bool{
return self.count> 3
}
}

In the above code snippet we can find that we are not passing count to isStringValid() function but thanks to self that we were able to access the count of the parent structure.

(III)With Closures: Consider the following piece of code

import UIKit
class ViewController: UIViewController{
override func viewDidLoad(){
super.viewDidLoad()
dummyFunction{
handle() //error
}
}

@IBAction func buttonTapped(_ sender: UIButton){
}

func dummyFunction(completionHandler: @escaping()-> ()){
completionHandler()
}

func handle(){
}
}

So in the above program if we try to access handle() function then that we cannot directly as shown above because we will get an error stating “Call to method ‘handle’ in closure requires explicit use of ‘self’ to make capture semantics explicit”. And thus the above program can be corrected and made to run just by adding self to handle as the following:

import UIKit
class ViewController: UIViewController{
override func viewDidLoad(){
super.viewDidLoad()
dummyFunction{[weak self] in
self?.handle()
}
}

@IBAction func buttonTapped(_ sender: UIButton){
}

func dummyFunction(completionHandler: @escaping()-> ()){
completionHandler()
}

func handle(){
}
}

So this was some of the usage of self.

Although there are many situations when we tend to use self unnecessarily for example consider the following code snippet

import UIKit
class ViewController: UIViewController{
override func viewDidLoad(){
super.viewDidLoad()
handle()//can be called directly
// self.handle() //not required
}

@IBAction func buttonTapped(_ sender: UIButton){
}

func dummyFunction(completionHandler: @escaping()-> ()){
completionHandler()
}

func handle(){
}
}

Now let’s move to the next part of the article which is Self. Self is used as a type. Let’s try to understand it further with help of examples. Consider the following piece of code:

struct Person{
static var country = "India"
var name:String
init(name: String){
self.name = name
}

func isValidName(){
print(name.isStringValid())
}

func printCompleteAddress(){
print("\(name) lives in \(country)") //error
}
}

In the above code snippet if we try to access country in the printCompleteAddress() function then that will throw an error stating “Static member ‘country’ cannot be used on instance of type ‘Person’ “ since Person is non static and country is static. In order to solve it there are two ways the first is to write the following

print(“\(name) lives in \(Person.country)”)

And the other way is to use Self as the following

print(“\(name) lives in \(Self.country)”)

The above Self will tell the person type and this is one of the scenario wherein we can use Self as a type.

Coming to the next use case.

Let’s say if we have created a button in ViewController and we have another XIV where we want to navigate to whenever the button is clicked so to do that we have to basically write a code to load XIVs.

Following represents the code for the same

class ViewController: UIViewController{
override func viewDidLoad(){
super.viewDidLoad()
handle()//can be called directly
// self.handle() //not required
}
@IBAction func buttonTapped(_ sender: UIButton){
let vc = HomeViewController.instantiateFromNib()
present(vc,animated: true)
}
func dummyFunction(completionHandler: @escaping()-> ()){
completionHandler()
}
func handle(){
}
}
extension UIViewController{
static func instantiateFromNib()-> Self{
func instantiateFromNib<T: UIViewController>(_viewType: T.Type)
->T{
return T.init(nibName: String(describing: T.self),bundle:
nil)
}
return instantiateFromNib(_viewType: self)
}
}

In the above code snippet we can make out that at line number 22 we are having a static function which we can call without having to create an instance of the class. This function is then having Self which basically declares that the function is going to return us an object that will be of type UIViewController . Then in line number 23 we are taking a generic parameter and also in line number 25 we are creating a Nib using generic code only. Also we are having bundle as nil since we are working with only one project, had there been multiple projects we would have included bundles as well. Next thing to be noticed is that self at line 28 represents the instance and not the type. Lastly in line number 9 we have created object using normal way and finally at line number 10 we have directly wrote present without having to use self.

So this wraps our article on self used for instance and Self used a type in Swift.

Enjoying!! I will be adding more post like this. Follow me so that you don’t miss any of them.

If you enjoyed reading this post, please share and give some claps so others can find it 👏👏👏👏👏 !!!!

You can follow me on medium for fresh articles. Also, subscribe me on youtube . It takes little effort from you to subscribe , but it gives me as a content writer some revenue and more motivation to make more content for you. So its my kind request to support me.

If you have any comment, question, or recommendation, feel free to post them in the comment section below!

--

--