Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "self" used for in Swift?

Tags:

ios

swift

self

I am new to Swift and I'm wondering what self is used for and why.

I have seen it in classes and structures but I really don't find them essential nor necessary to even mention them in my code. What are they used for and why? In what situations it's necessary to use it?

I have been reading lots of questions and answers for this question but none of them fully answers my questions and they always tend to compare it with this as in Java, with which I'm not familiar whatsoever.

like image 200
Lucas Martin Calderon Avatar asked Nov 10 '14 00:11

Lucas Martin Calderon


People also ask

Why do we use self in Swiftui?

Outside of initializers, the main reason for using self is because we're in a closure and Swift requires it so we're clear we understand what's happening. This is only needed when accessing self from inside a closure that belongs to a class, and Swift will refuse to build your code unless you add it.

What is self type in Swift?

From the Swift Programming Language Book: The Self type isn't a specific type, but rather lets you conveniently refer to the current type without repeating or knowing that type's name. In a protocol declaration or a protocol member declaration, the Self type refers to the eventual type that conforms to the protocol.

When would you use self in a method?

You use self when: Defining an instance method. It is passed automatically as the first parameter when you call a method on an instance, and it is the instance on which the method was called. Referencing a class or instance attribute from inside an instance method.

Is self optional in Swift?

The [unowned self] in Swift In Swift, a weak reference makes the variable optional. This is because the variable could be nil. But you can also create a weak reference that does not make the variable optional. This is possible using the unowned keyword.


1 Answers

Yes it is the same as this in Java and self in Objective-C, but with Swift, self is only required when you call a property or method from a closure or to differentiate property names inside your code, such as initializers. So you can use almost all of your class components safely without using self unless you are making the call from a closure.

“The self Property Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself. You use the self property to refer to the current instance within its own instance methods.

The increment() method in the example above could have been written like this:

func increment() {     self.count += 1 } 

In practice, you don’t need to write self in your code very often. If you don’t explicitly write self, Swift assumes that you are referring to a property or method of the current instance whenever you use a known property or method name within a method. This assumption is demonstrated by the use of count (rather than self.count) inside the three instance methods for Counter.

The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way. You use the self property to distinguish between the parameter name and the property name.

Here, self disambiguates between a method parameter called x and an instance property that is also called x:”

Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2 Prerelease).”


This is how Ray Wenderlich recommends the use of self in Swift for their tutorials:

Use of Self

For conciseness, avoid using self since Swift does not require it to access an object's properties or invoke its methods.

Use self when required to differentiate between property names and arguments in initializers, and when referencing properties in closure expressions as required by the compiler:

class BoardLocation {   let row: Int, column: Int    init(row: Int, column: Int) {     self.row = row     self.column = column      let closure = {       println(self.row)     }   } } 

And this is GitHub's recommendations on self for their applications:

Only explicitly refer to self when required

When accessing properties or methods on self, leave the reference to self implicit by default:

private class History {     var events: [Event]      func rewrite() {         events = []     } } 

Only include the explicit keyword when required by the language — for example, in a closure, or when parameter names conflict:

extension History {     init(events: [Event]) {         self.events = events     }      var whenVictorious: () -> () {         return {             self.rewrite()         }     } } 

Rationale: This makes the capturing semantics of self stand out more in closures, and avoids verbosity elsewhere.

like image 159
David Gomez Avatar answered Sep 22 '22 11:09

David Gomez