iosswiftdesign-patternsclass-cluster

Custom class clusters in Swift


This is a relatively common design pattern:

https://stackoverflow.com/a/17015041/743957

It allows you to return a subclass from your init calls.

I'm trying to figure out the best method of achieving the same thing using Swift.

I do know that it is very likely that there is a better method of achieving the same thing with Swift. However, my class is going to be initialized by an existing Obj-C library which I don't have control over. So it does need to work this way and be callable from Obj-C.

Any pointers would be very much appreciated.


Solution

  • I don't believe that this pattern can be directly supported in Swift, because initialisers do not return a value as they do in Objective C - so you do not get an opportunity to return an alternate object instance.

    You can use a type method as an object factory - a fairly contrived example is -

    class Vehicle
    {
        var wheels: Int? {
          get {
            return nil
          }
        }
    
        class func vehicleFactory(wheels:Int) -> Vehicle
        {
            var retVal:Vehicle
    
            if (wheels == 4) {
                retVal=Car()
            }
            else if (wheels == 18) {
                retVal=Truck()
            }
            else {
                retVal=Vehicle()
            }
    
            return retVal
        }
    
    }
    
    class Car:Vehicle
    {
        override var wheels: Int {
          get {
           return 4
          }
        }
    }
    
    class Truck:Vehicle
    {
        override var wheels: Int {
          get {
              return 18
           }
         }
    }
    

    main.swift

    let c=Vehicle.vehicleFactory(4)     // c is a Car
    
    println(c.wheels)                   // outputs 4
    
    let t=Vehicle.vehicleFactory(18)    // t is a truck
    
    println(t.wheels)                   // outputs 18