在实例方法中调用类型方法 [英] Calling Type Methods Within An Instance Method
问题描述
Apple对类型(类)方法有一个很好的解释 Here 。
Apple has a nice explanation of Type (Class) Methods Here.
但是,他们的示例如下所示:
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.
然而,我我需要在我的类的一个实例中调用我的Type方法,而这似乎无法计算。
However, I need to call my Type Method from within an instance of my class, and that don't seem to compute.
我必须做错事,但我注意到Apple还不支持Class Properties :(。我想知道我是否会去干井用水。
I MUST be doing something wrong, but I noticed that Apple does not yet support Class Properties :(. I am wondering if I am going to a drywell for water.
这是我尝试过的(在操场上):
Here is what I have tried (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?
推荐答案
var staticRet:String = ClassA.staticMethod()
这有效。它不需要任何参数,因此您不需要传入任何参数。你也可以像这样动态获得ClassA:
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()
这篇关于在实例方法中调用类型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!