Using Self in Extensions for Swift

Improving compiler performance with no real effort

Extensions are extremely important in Swift. You can also add ‘self ‘ to an extension. What does that mean though?

Image for post
Image for post
Photo by Mathieu Stern on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

  • Be able to produce a “Hello, World!” iOS application (guide HERE)
  • Knowledge of classes, structures and enums (guide HERE)
  • Some knowledge of extensions would be useful (guide HERE)

Terminology

class: An object defined in Swift, using pass by reference semantics (reference)

extensions: Extensions add new functionality to a class, struct, enum or protocol

instance: An example or single occurrence of something

mutating: A keyword that can be added to a function that enables it to change a variable

self: A property on an instance that refers to itself

What is an extension?

We can extend aclass , a struct, a enum or aprotocol.

extension TargetType {
// functionality that will be added to the type
}

we can add an extension to existing types that are used in Swift.

A real-world example

For this tutorial we are going to add an increment function to Int in Swift. Using an extension.

Perhaps you want to add an

extension Int {
var increment: Int {
return self + 1
}
}

which is called by

3.increment

Now there are a few interesting things going on here. Let us look at these in turn.

increment is a read-only computed property that calculates the increment of the Integer that is given.

self refers to the integer we have used with the extension. In this case it is 3.

The results: we are not actually changing the original Integer value

We have used self correctly, but the function is not mutating

We can see this by creating a variable to use this functionality.

var myNum = 3
myNum.increment // 4
print (myNum) // 3

Editing the functionality of the extension

extension Int {
var increment: Int {
return self + 1
}
mutating func incrementVal() {
self = self + 1
}
}

We can now call the mutating function, which means that we can implement our increment at last!

var myNum = 3
myNum.incrementVal() // 4

Conclusion

self is not something to be concerned about when coding Swift, it simply means that in an extension we can refer to the instance that we have called the function from.

This gives a good bit of flexibility to Swift coding, and gives you some extra tools in that coding toolbox.

Excellent stuff

I hope you enjoyed this article, and get in contact with me if you’ve any questions or concerns…

Want to get in contact? Try the link here:

https://twitter.com/stevenpcurtis

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store