Schmo
Schmo

Reputation: 353

Is it possible to specify self to methods in Swift?

If you have several compatible objects:

class Animal { ... }

class Mammal: Animal { ... }

class Platypus: Mammal {

  override func walk() {
    if something {
      Animal.walk(self: self)
    } else {
      Mammal.walk(self: self)
    }
  }
}

And, let's say, you want to call one super's method in one case, but the other super's method in the other, would it be possible to pass self explicitly as an argument?

The question is provoked by the following hint in Xcode. Xcode suggests methods when you type dot after a class name

What does this suggestion really mean?

Upvotes: 1

Views: 800

Answers (2)

Keiwan
Keiwan

Reputation: 8251

@Sulthan's answer correctly shows how you can pass self to superclass functions. I just want to explain and visualize a little bit what that XCode suggestion is.

If you look closely (or try it out) you'll see that calling the function in the suggested way will not actually call it but rather return it.

Since f is an instance method it can only be called on an instance. If you call X.f(...) you have to pass an instance of X to be able to call f on that instance.

So for example, if you have:

class X {
    var description: String

    init(desc: String) {
        description = desc
    }

    func f() {
        print(description)
    }
}

and then you say

var function = X.f(X(desc: "A specific description"))  // passing an instance of X

then you can call the function with

function()

and you will see

A specific description   

alternatively you could have also immediately called the function with:

X.f(X(desc: "A specific description"))()

Or:

X(desc: "A specific description").f()

Upvotes: 4

Sulthan
Sulthan

Reputation: 130102

This is completely possible, if you use static dispatch

class Animal {
   static func walk(_ animal: Animal) {
     ...
   }
}

class Mammal : Animal {
   static func walk(_ mammal: Mammal) {
     ...
   }
}

However, it is very strange from architecture point of view. It breaks polymorphism.

Note that you won't be able to call animal.walk() on an instance anymore. You would have to also define a separate instance method.

Upvotes: 1

Related Questions