简体   繁体   English

如何在Swift中从另一个类扩展中调用类函数

[英]How to call a class function from within another classes extension in Swift

So say if I have a Class A. Then I create a new swift file for class B where it would look like this: 假设我有A类。然后为B类创建一个新的swift文件,它看起来像这样:

extension Class A {

 public Class B: Superclass {

  public class func doSomething() { }

 }

}

Now how would I make the call to doSomething() ? 现在,我将如何调用doSomething()

If you want to add an inner class to an existing class via an extension, you can do it like this: 如果要通过扩展将内部类添加到现有类中,则可以这样进行:

public class A {

}

public extension A {

    public class B {

        public class func doSomething() {
            print("hello")
        }

    }

}

Note there is no Superclass involved. 注意不涉及Superclass

Since doSomething is a class method, you can call it like this: 由于doSomething是一个类方法,因此可以这样调用它:

A.B.doSomething() // "hello"

If you are trying to define a subclass of A , then you should do this: 如果要定义A的子类,则应执行以下操作:

public class A {

}

public class B: A {

        public class func doSomething() {
            print("hello")
        }

}

B.doSomething() // "hello"

How do you feel about this: 你觉得这个怎么样:

 public class A {
        var innerClass = InnerClass()
 }

extension A {
    public class InnerClass {   
            public class func doSomething() { }
    }   
}

public class C {
    var test = A().innerClass
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM