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

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

本文介绍了如何在实例方法中调用类型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apple有一个很好的类型说明(类)方法,但是,它们的示例如下所示:

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.

我必须做错了事,但我注意到Apple尚不支持类属性.我想知道我是否在浪费时间.

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.

我在操场上尝试过

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()

有人对我有线索吗?

推荐答案

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:

快捷键2

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

快捷键3

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

这篇关于如何在实例方法中调用类型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 12:37