Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Type Methods within an instance method

Apple has a nice explanation of Type (Class) Methods, however, their example looks like this:

class SomeClass {     class func someTypeMethod() {         // type method implementation goes here     } } SomeClass.typeMethod() 

I see this exact same example parroted everywhere. My problem is, I need to call my Type Method from within an instance of my class, and that doesn't seem to compute.

I MUST be doing something wrong, but I noticed that Apple does not yet support Class Properties. I'm wondering if I'm wasting my time.

I tried this in a playground:

class ClassA {     class func staticMethod() -> String { return "STATIC" }      func dynamicMethod() -> String { return "DYNAMIC" }      func callBoth() -> ( dynamicRet:String, staticRet:String )     {         var dynamicRet:String = self.dynamicMethod()         var staticRet:String = ""  //        staticRet = self.class.staticMethod() // Nope //        staticRet = class.staticMethod() // No way, Jose //        staticRet = ClassA.staticMethod(self) // Uh-uh //        staticRet = ClassA.staticMethod(ClassA()) // Nah //        staticRet = self.staticMethod() // You is lame //        staticRet = .staticMethod() // You're kidding, right? //        staticRet = this.staticMethod() // What, are you making this crap up? //        staticRet = staticMethod()  // FAIL          return ( dynamicRet:dynamicRet, staticRet:staticRet )     } }  let instance:ClassA = ClassA() let test:( dynamicRet:String, staticRet:String ) = instance.callBoth() 

Does anyone have a clue for me?

like image 722
Chris Marshall Avatar asked Jun 29 '14 01:06

Chris Marshall


People also ask

Can instance methods call class methods?

Note that you can call a classmethod from an instance method with no problems, so you may not actually have to make as many changes as you think.

Can an instance method call an instance method?

In order to call an instance method, you need an instance. So a static method can call an instance method as long as it has a reference to an instance to call it on. Show activity on this post. Static methods can be called freely, but instance methods can only be called if you have an instance of the class.

How do you call a method in another method in Python?

The Function which calls another Function is called Calling Function and function which is called by another Function is call Called Function. How does Function execution work? A stack data structure is used during the execution of the function calls.


1 Answers

var staticRet:String = ClassA.staticMethod() 

This works. It doesn't take any parameters so you don't need to pass in any. You can also get ClassA dynamically like this:

Swift 2

var staticRet:String = self.dynamicType.staticMethod() 

Swift 3

var staticRet:String = type(of:self).staticMethod() 
like image 88
Connor Avatar answered Oct 05 '22 20:10

Connor