Type of ‘self’ in Swift

In Swift, we have the following types of ‘self’ keyword

  1. Postfix self
  2. Prefix self
  3. Self (uppercase S)
  4. self (lowercase s)

Postfix .self:

The postfix .self, refers to the metatype type of the type on which it is called.

In this case, AnyClass.self returns AnyClass itself, not an instance of AnyClass. And SomeProtocol.self freturns SomeProtocol itself, not an instance of a type that conforms to SomeProtocol at runtime. A very common example, we create a subclass of UITableViewCell/UICollectionViewCell (say BaseCollectionViewCell)

class BaseCollectionViewCell: UICollectionViewCell {....}

then for UICollectionView cell registration, we use

yourCollectionView.register(BaseProductCollectionViewCell.self, forCellWithReuseIdentifier: "cellIdentifierProduct")

Prefix self:

In other programming languages call it this and it refers to the instance of the enclosing type. You use it, either explicitly or implicitly, when referring to members of the enclosing type.

Example:

struct Person {    
let name: String
init(name: String) {
self.name = name // here self refering member of enclosing type. In Swift it is not mandatory to use self.
}
}

Self (uppercase S):

When used with a capital S, Self refers to the type that conforms to the protocol, e.g. String or Int.

Example:

extension BinaryInteger {
func squared() -> Self {
return self * self
}
}

In the example above, Int conforms to BinaryInteger, so when called on Int the method returns an Int.

another example

extension SomeProtocolName where Self: UIView 
{
func someFunction() {
self.layer.shadowColor = UIColor.red.cgColor
}
}

self (lowercase s):

When used with a lowercase S, self refers to the value inside that type.

extension BinaryInteger {
func squared() -> Self {
return self * self
}
}

In the above example were called on an Int storing the value 10 it would effectively be 10*10

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Swift 5.5 Concurrency backward compatibility

Why You Should Use Xcode Instruments in Your iOS Apps

SnapKit for iOS

How to Play Custom Audio in Swift Playgrounds for iPad

Shared Element Transition in Navigation Architecture Component

10 Reasons Why Swift is the Best Language for iOS Development

Working with inout references in Swift

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
Gagan Vishal

Gagan Vishal

More from Medium

Everyone can code Puzzles — Hypocycloid

Basic Operators in Swift

[Swift] Struct vs Class

Create Swift Framework + Cocoapods