Remove unnecessary "self" references

Photo by Jack Guo on Unsplash

Remove unnecessary "self" references

Although in the earlier versions of Swift that was necessary now we don't need them anymore. I've seen some developers unaware of this or insist on writing the old way. We should only use "self" when the compiler insists, like in escaping closures or initializers. Unlike Objective-C, you can skip "self" when accessing object properties or methods. This makes your code clearer and easier to read.

private func configureTitleLabel() {
    self.titleLabel.numberOfLines = 0
    self.titleLabel.textColor = .systemGray
    self.titleLabel.font = .bold16
    self.titleLabel.text = "Title"
}

Our code can be written more concisely without any loss of clarity or functionality:

private func configureTitleLabel() {
    titleLabel.numberOfLines = 0
    titleLabel.textColor = .systemGray
    titleLabel.font = .bold16
    titleLabel.text = "Title"
}

You may also consider eliminating the extra self when capturing the weak self.

NetworkManager.getComments(by: randomInt) { [weak self] result in
    // Check if self still exists
    guard let self = self else { return }
    // Some work to do
    self.someMethod()
}

In this example, [weak self] captures a weak reference to self within the closure. The guard let self = self else { return } pattern ensures that self is safely unwrapped and used only if self still exists. This helps prevent strong reference cycles when dealing with asynchronous tasks. Instead of the example belove we could write it this way.

NetworkManager.getComments(by: randomInt) { [weak self] result in
    // Check if self still exists
    guard let self else { return }
    // Some work to do
    self.someMethod()
}

Let's take another step forward with implicit self references inside closures. After unwrapping the weak self we do not need to reference self explicitly.

NetworkManager.getComments(by: randomInt) { [weak self] result in
    // Check if self still exists
    guard let self else { return }
    // Some work to do
    someMethod()
}

In the short run, I'll be sharing new posts more often. Thanks for reading it!