7

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?

sandeep.gosavi
  • 610
  • 2
  • 10
  • 27
J.beenie
  • 861
  • 10
  • 22
  • 4
    A caseless `enum` is a good option, see for example http://stackoverflow.com/q/38585344/2976878 – Hamish Mar 21 '17 at 18:48
  • Thanks, that was a very helpful link. So essentially, the use of enum ensure that it can't be instantiated, and then you simply just make all of the functions and properties static! Genius! – J.beenie Mar 21 '17 at 18:55
  • 1
    Precisely – it's what's used for the stdlib's [`Never`](https://developer.apple.com/reference/swift/never) type, which cannot be instantiated. – Hamish Mar 21 '17 at 18:58

3 Answers3

10

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

Code Different
  • 90,614
  • 16
  • 144
  • 163
9

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()
Jens Meder
  • 4,237
  • 1
  • 25
  • 25
1

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