Universal “Self” Power(💪) of swift 5.1

MdNiks
2 min readJul 15, 2019

--

Welcome guys,

Today we have discussed about new features or you can says key point of swift 5.1 universal “Self”. 👇

So here we can start with small story ;). Story means a technical type story. It’s not like an old grandmother type bed time story.😜

Nowadays all developers are creating common code for network call class Right?

In Network or you can say API calling class, it’s having one class variable and method so whenever API calls are triggered, we have to manage that class variable value and if class variable reaches max count of API we have put console or you can put error message.

class NetworkOrAPIManager {

class var maxActiveRequests: Int {

return 3

}

func printDebugData() {

print(“Maximum network requests: \. (NetworkOrAPIManager.maxActiveRequests).”)

}

}

let objManager = NetworkOrAPIManager()

objManager.printDebugData()

Output is : Maximum network requests: 3.

But the story is never ending without tragedy Right?, So now we have created one more class it’s subclass of network class.

class ChildNetworkManager: NetworkOrAPIManager {

override class var maxActiveRequests: Int {

return 1

}

}

let manager = ChildNetworkManager()

manager.printDebugData()

Output is : Maximum network requests: 3.

Hey! What’s going on! We have an overridden class variable, but still, it prints parent class variable value.🤔🤔🤔🤔🤔🤔🤔

Due to that we need to utilize “Self”. Swift’s use of Self so that it refers to the containing class variable when used inside classes, structs, and enums. This is particularly useful for dynamic types, where the exact type of something needs to be determined at runtime. 🤘

class NetworkOrAPIManager {

class var maxActiveRequests: Int {

return 3

}

func printDebugData() {

print(“Maximum network requests: \(Self.maximumActiveRequests).”)

}

}

let manager = ChildNetworkManager()

manager.printDebugData()

Output is : Maximum network requests: 1.

So, all is well that ends well!!

Just use it. w00t! How cool is that and all done with just
a few lines of code!

If you have any comments or questions, please respond below! I’d love to hear from you.

--

--

MdNiks

I'm an accomplished iOS programmer with more than 12 years of experience working in a collaborative environment with tight deadlines.