我有一个类TestClass和一个类和实例方法
class TestClass {
class func classMethod(){
print("how do i call instance method from here")
}
func instanceMethod(){
print("call this instance method")
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我如何调用instanceMethod从classMethod?
我注意到的一种方式是
class func classMethod(){
TestClass().instanceMethod()
}
Run Code Online (Sandbox Code Playgroud)
但是,这是一个好方法吗?
从设计的角度来看,您尝试做的事情很少有任何意义.
根据定义,instance method在一个工作instance对象.例如,它可能需要访问某些实例成员,或以某种方式插入您调用该方法的对象的状态.
class 另一方面,方法不要求实例能够调用它们 - 并且通常应仅对给定参数进行操作,而不是依赖于共享状态.
如果您需要调用instanceMethod()的classMethod(),并且instanceMethod()不需要任何状态-这是为什么它不也是一种class方法,或者(全球)纯函数?
| 归档时间: |
|
| 查看次数: |
240 次 |
| 最近记录: |