1

I want to "make" a number of class instances similar to a base class but different in underlying type. (Not quite the same as the typical "Animal" class factory examples seen all over the net!)

The code below is close to working but it requires the user to "upcast" the make result, as in:

var f1 = FOO.make(version: FOO.Ver.f1) as! FOO1_32

I do not want the user to know about the specific class type other than it is a FOO. I have seen other proposals and they all indicate that the solution is to define the make with a generic type that conforms to the protocol as in:

make<T: FOOProtocol>(version: Ver = .f1) -> T

However this gives me the error "generic parameter 'T' could not be inferred" on the call to FOO.make(version: FOO.Ver.f1)

Anyone know how to do this? My Playground code follows.

protocol FOOProtocol
{
    associatedtype FOOtype
    var value: FOOtype {get set}
}

class FOO
{
    enum Ver
    {
        case f1
        case f2
    }

    class func make(version: Ver = .f1) -> FOO
    {
        print("FOO make")
        switch version
        {
        case .f1:
            return FOO1_32()

        case .f2:
            return FOO2_64()
        }
    }
}

class FOO1_32: FOO, FOOProtocol
{
    typealias FOOtype = UInt32

    private var fooVal: UInt32 = 0
    var value: UInt32
    {
        get { return self.fooVal }
        set { self.fooVal = newValue }
    }

    override init()
    {
        print("FOO1_32 init")
        self.fooVal = 132
    }
}

class FOO2_64: FOO, FOOProtocol
{
    typealias FOOtype = UInt64

    private var fooVal: UInt64 = 0
    var value: UInt64
    {
        get { return self.fooVal }
        set { self.fooVal = newValue }
    }

    override init()
    {
        print("FOO2_64 init")
        self.fooVal = 264
    }
}

var f1 = FOO.make(version: FOO.Ver.f1)  // requires: as! FOO1_32
let f1v = f1.value
print("\(f1v)")

var f2 = FOO.make(version: FOO.Ver.f2)  // requires: as! FOO2_64
let f2v = f2.value
print("\(f2v)")
Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
WholeCheese
  • 437
  • 3
  • 14

0 Answers0