Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Instantiate class (AnyClass) conforming to protocol

I want to implement something like "registerClassForAction". For that purpose, I have defined a protocol:

@objc protocol TestProt {
    func testMe() -> String
}

Let's do a class declaration:

class TestClass: NSObject, TestProt {
    func testMe() -> String {
        return "test"
    }
}

I define the function to register the object in another class:

func registerClassForAction(aClass: AnyClass) { ... }

Switching to the REPL, I'd simulate the register method:

let aClass: AnyClass = TestClass.classForCoder() //or .self
let tClass = aClass as NSObject.Type
let tInst = tClass() as TestProt
tInst.testMe()

This currently works but is there another way to instantiate tClass, other than with

let tClass = aClass as NSObject.Type

Reason for asking, I'd like to explore the chance of getting rid of the NSObject so my TestClass does not to inherit from NSObject. Delegation was considered, but I'd like to control the lifetime of tInst and be able to dealloc it at a specific point in time.

thanks for helping

Ron

like image 556
Ron Avatar asked Feb 23 '15 02:02

Ron


1 Answers

This is possible in Swift 2.0 without requiring @objc or subclassing NSObject:

protocol TestProt {
    func testMe() -> String
}

class TestClass: TestProt {

    // This init is required in order
    // to construct an instance with
    // a metatype value (class.init())
    required init() {
    }

    func testMe() -> String {
        return "Hello from TestClass"
    }
}

let theClass = TestClass.self
let tInst: TestProt = theClass.init()

tInst.testMe()

enter image description here

like image 155
Steve Wilford Avatar answered Oct 19 '22 01:10

Steve Wilford