Are static classes supported by Swift?

≯℡__Kan透↙ 提交于 2019-12-06 08:27:43

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 { ... }

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

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
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!