Ios 类方法中的实例方法

Ios 类方法中的实例方法,ios,swift,function,Ios,Swift,Function,我有一个TestClass类和一个class&instance方法 class TestClass { class func classMethod(){ print("how do i call instance method from here") } func instanceMethod(){ print("call this instance method") } } 我的问题是如何从classMetho

我有一个TestClass类和一个class&instance方法

class  TestClass {

    class func classMethod(){

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

    }

    func instanceMethod(){

        print("call this instance method")

    }


}
我的问题是如何从classMethod中调用instanceMethod

我注意到的一个方面是

class func classMethod(){

   TestClass().instanceMethod()

}

但是,这是一种好方法吗?

要调用实例方法,您需要一个TestClass实例。这就是TestClass在调用TestClass.instanceMethod时得到的结果

如果要从特定实例调用它,可以将其作为参数传递给class函数:class func classMethodUsingInstanceinstance:TestClass


如果你不需要一个特定的实例来实现,也可以考虑将它作为一个类方法。

调用实例方法,你需要一个TestC类实例。这就是TestClass在调用TestClass.instanceMethod时得到的结果

如果要从特定实例调用它,可以将其作为参数传递给class函数:class func classMethodUsingInstanceinstance:TestClass


如果您不需要一个特定的实例来实现,也可以考虑将它作为一个类方法。

您可以将实例对象作为参数传递给类方法,然后调用对象的实例方法:

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")
    }
}

可以将实例对象作为参数传递给类方法,然后调用该对象的实例方法:

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")
    }
}

从设计的角度来看,您尝试做的事情很少有意义

根据定义,实例方法对对象的实例进行操作。 例如,它可能需要访问某些实例成员,或者以某种方式干预调用该方法的对象的状态

另一方面,类方法不要求实例能够调用它们,并且通常只对给定的参数进行操作,而不依赖于共享状态


如果您需要在classMethod中调用instanceMethod,并且instanceMethod不需要任何状态-为什么它不是一个类方法,或者一个全局纯函数?

从设计角度来看,您尝试做的很少有意义

根据定义,实例方法对对象的实例进行操作。 例如,它可能需要访问某些实例成员,或者以某种方式干预调用该方法的对象的状态

另一方面,类方法不要求实例能够调用它们,并且通常只对给定的参数进行操作,而不依赖于共享状态


如果您需要在classMethod中调用instanceMethod,instanceMethod不需要任何状态-为什么它不是一个类方法或全局纯函数?

在这一点上,类方法也可以变成一个实例方法在那一点上,类方法也可以变成一个实例方法