In the process of learning the
swift language, you will constantly find some unbelievable syntax of
swift. After learning it, I often ask myself, “Is it really necessary? Before learning it, who would have thought that
Self are different?
Scenario 1 Prefix
self. is the most commonly used scenario, when the keyword
self, similar to the
this keyword in other languages, represents the instance of the current code run during the coding process.
Note that the prefix self. represents an instance object of the current type. In type definitions, if the prefix self. appears in an embedded type or anonymous function, be aware of what it refers to. This is somewhat similar to the confusing
this in es6.
In es6, the keyword
this, has nothing to do with functions, objects or classes, but only with the execution context.
Scenario 2 postfix
You can use the postfix self expression to access a type as a value. For example, SomeClass.self returns SomeClass itself, not an instance of SomeClass. And SomeProtocol.self returns SomeProtocol itself, not an instance of a type that conforms to SomeProtocol at runtime.
.self, returns the corresponding
type (type), not the
The most common place to see this is in object deserialization operations, such as :
Looking at the function definition of decode, you can see that
Foo.self represents a meta-type of type
When I first saw the Self keyword, I thought it was the same thing as self, so I should just pay attention to the prefix and postfix. However, looking at the context, the symbol
. does not appear at all where Self is used.
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.
Extends a single property:
Self keyword is a simple way of writing code for the type
Foo and has no other properties of its own.