8

I want to be able to store a class as a variable, so I can call class methods out of it later, something like this:

class SomeGenericItem: NSObject { var cellClass: AnyClass init(cellClass: AnyClass) { self.cellClass = cellClass } func doSomething(p1: String, p2: String, p3: String) { self.cellClass.doSomething(p1, p2: p2, p3: p3) } } class SomeClass: NSObject { class func doSomething(p1: String, p2: String, p3: String) { ... } } 

I want to be able to say something like:

let someGenericItem = SomeGenericItem(cellClass: SomeClass.self) someGenericItem.doSomething("One", p2: "Two", p3: "Three") 

What I'm trying to figure out is:

1) How would a protocol be defined so I could call class func doSomething?
2) What would the declaration of cellClass need to be?
3) What would the call look like?

1 Answer 1

3

Protocols can't define class methods, but static methods are fine. You'll need your wrapper to be generic, and specify a 'where' constraint that guarantees the wrapped type's conformance to your protocol.

Example:

protocol FooProtocol { static func bar() -> Void } class FooishClass : FooProtocol { static func bar() -> Void { println( "FooishClass implements FooProtocol" ) } } class FooTypeWrapper< T where T: FooProtocol > { init( type: T.Type ) { //no need to store type: it simply is T } func doBar() -> Void { T.bar() } } 

Use:

let fooishTypeWrapper = FooTypeWrapper( type: FooishClass.self ) fooishTypeWrapper.doBar() 
Sign up to request clarification or add additional context in comments.

4 Comments

I'm finding this works, but with an odd problem. I can only get this to work if the FooProtocol is in the same file as the call to "let fooishTypeWrapper = FooTypeWrapper( type: FooishClass.self )". If it's in a different file, Swift complains about the declaration of "class FooishClass : FooProtocol" saying "Type 'Foolish Class' does not conform to protocol 'Foo Protocol'", even though it does. The only difference is which file the protocol is in. This has caused me to get this approach to work one time, but as soon as I try to use it in multiple files I can't compile. Any ideas?
Just double checked, works absolutely fine. You probably have a typo somewhere - post your code if the issue persists.
"Protocols can't define class methods" This is not true. Protocols declare type method requirements with static. Type method requirements can be satisfied by classes using either class methods or static methods.
Do you know of a way to add a default argument to init? e.g. init(type: T.Type = FooishClass.self) I can't get it to work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.