Are static classes supported by Swift?

2019-05-20 03:44发布

I would like to know if you can create static classes in swift similar to those in C# i.e. a class that cannot be instantiated which can only have static functions and static properties. Are these types of classes possible in swift?

If not, what is the most efficient way to recreate such a design pattern given the tools available within Swift?

3条回答
时光不老,我们不散
2楼-- · 2019-05-20 04:12

You can get the same functionality by making the initializer private and use static/class keyword before properties and methods.Using final keyword makes sure your class cannot be subclassed and if you use final, static methods don't make sense anymore because they cannot be overridden.

class Bar{
    private init(){}
    static let x = 10

    class func methodA(){
        //do something
    }

    static func methodB(){
        // do something else
    }
}
查看更多
干净又极端
3楼-- · 2019-05-20 04:31

No, Swift has no concept of a static class. But if you have no assignable property anyway, what difference will initialization make? I can think of 2 options:

  • Mark the class as final so it cannot be inherited: final class MyClass { .... }

  • Use a struct, which has no inheritance: struct MyUtilities { ... }

查看更多
女痞
4楼-- · 2019-05-20 04:32

Yes, that is possible. You just need to define your class as final and make the constructor private, e.g.

final class Test {
   private init() {

   }

   static func hello() {
      print("hello")
   }
 }

 Test.hello()
查看更多
登录 后发表回答