user6398734
user6398734

Reputation:

instance methods from class methods swift

I have a class TestClass and a class & instance method inside it

class  TestClass {

    class func classMethod(){

       print("how do i call instance method from here")

    }

    func instanceMethod(){

        print("call this instance method")

    }


}

My question is how do i call that instanceMethod from classMethod??

One way i have noticed is

class func classMethod(){

   TestClass().instanceMethod()

}

But,Is this the good way to do?

Upvotes: 2

Views: 879

Answers (3)

David Ganster
David Ganster

Reputation: 1993

What you are trying to do rarely makes any sense from a design perspective.

By definition, an instance method operates on an instance of an object. For example, it might require access to some instance members, or somehow meddle with the state of the object you call the method on.

class methods on the other hand do not require an instance to be able to call them - and should in general only operate on the given parameters, not be dependant on shared state.

If you need to call instanceMethod() in classMethod(), and instanceMethod() does not require any state - why is it not also a class method, or a (global) pure function?

Upvotes: 5

rosewater
rosewater

Reputation: 624

You can pass the instance object as a parameter to the class method, and then call the instance method of the object:

class  TestClass {

    class func classMethod(obj:TestClass){

       print("how do i call instance method from here")
       obj.instanceMethod()
    }

    func instanceMethod(){

        print("call this instance method")
    }
}

Upvotes: 1

Wyatt
Wyatt

Reputation: 309

To call the instance method, you need an instance of TestClass. That's what TestClass() is getting you when you call TestClass().instanceMethod().

If you want to call it from a specific instance, you could pass it in as a parameter to the class function: class func classMethodUsingInstance(instance: TestClass)

If you don't need a specific instance for instanceMethod(), maybe consider making it a class method as well.

Upvotes: 0

Related Questions