Search code examples
swiftnsarrayprotocolsswift2swift-array

NSObject class conforms to protocol contained in NSArray with Swift


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.


Solution

  • Don't try to write Objective-C in Swift. Move away from NSObject, NSArray and NSMutableArray.

    Here is your code without any Objective-C types:

    func createManagers() -> [Manager] {
        let result = [Manager]()
        for (index, aClass) in classes.enumerate() {
            // TODO: do something and fill the result array
        }
        return result
    }
    

    If you want to ensure your return types are a subclass of NSObject:

    func createManagers<T: NSObject where T: Manager>() -> [T] {
        var result = [T]()
        for (index, aClass) in classes.enumerate() {
            // TODO: do something and fill the result array
        }
        return result
    }