ios 如何在实例方法中调用类型方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24472399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:09:51  来源:igfitidea点击:

How to call Type Methods within an instance method

iosclassmethodstypesswift

提问by Chris Marshall

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

Apple对 Type (Class) Methods有很好的解释,但是,他们的示例如下所示:

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.

我一定是做错了什么,但我注意到 Apple 还不支持类属性。我在想我是不是在浪费时间。

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?

有人对我有线索吗?

回答by Connor

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:

这有效。它不需要任何参数,因此您无需传入任何参数。您还可以像这样动态获取 ClassA:

Swift 2

斯威夫特 2

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

Swift 3

斯威夫特 3

var staticRet:String = type(of:self).staticMethod()

回答by Diogo T

In Swift 3 you can use:

在 Swift 3 中,您可以使用:

let me = type(of: self)
me.staticMethod()