I would like to create a method in Swift that returns an array of NSObject objects that conform to a protocol. I've tried something like this:
func createManagers() -> [Manager] {
let result = NSMutableArray(capacity: self.classes.count)
(self.classes as NSArray).enumerateObjectsUsingBlock { (object: AnyObject!, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
// TODO: do something and fill the result array
}
return result as NSArray as! [Manager]
}
Manager
is a protocol as you see. I am receiving the error that the cast at the return statement will always fail.
I want to tell the compiler that I have an array of objects of NSObject type and all elements conform to Manager protocol.
Don't try to write Objective-C in Swift. Move away from
NSObject
,NSArray
andNSMutableArray
.Here is your code without any Objective-C types:
If you want to ensure your return types are a subclass of
NSObject
: