I have Objective-C Protocol and Interface implementation as below:
@protocol Animal <NSObject>
-(void)walk;
@end
@interface Cat : NSObject<Animal>
@end
@implementation Cat
-(void)walk{}
@end
@interface Dog : NSObject<Animal>
@end
@implementation Dog
-(void)walk{}
@end
I am trying to use instance of classes at runtime which implement protocol 'Animal'. This code in in swift :
var classesCount = objc_getClassList(nil, 0)
let allClasses = UnsafeMutablePointer<AnyClass?>.allocate(capacity: Int(classesCount))
classesCount = objc_getClassList(AutoreleasingUnsafeMutablePointer(allClasses), classesCount)
for i in 0..<classesCount{
let cls : AnyClass! = allClasses[Int(i)]
if class_conformsToProtocol(cls, Animal.self){
let instance = cls.self.init()
instance.walk()
}
}
Tried many ways to get instance from AnyClass, AnyObject, and NSObject. I am facing compiler errors in doing so. Error for this code snippet is:
'required' initializer 'init(arrayLiteral:)' must be provided by subclass of 'NSSet'.
Is there any way to get instances of 'Cat' and 'Dog'?