0

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.

Infinite Possibilities
  • 7,415
  • 13
  • 55
  • 118

2 Answers2

1

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
}
vrwim
  • 13,020
  • 13
  • 63
  • 118
  • , can you please point me to the documentation where I can read more about this? Thank you! – Infinite Possibilities Jun 18 '15 at 11:29
  • 1
    [here](https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html) is the documentation on Swift generics. – vrwim Jun 18 '15 at 11:32
0

Your return type is a Dictionary with key NSObject and value type Manager, instead of an array. Change the return type to [Manager]. Also you probably want to use the map function of array:

func createManagers() -> [Manager] {
    return classes.map { doSomethingAndTransformIntoManager($0) }
}
lammert
  • 1,456
  • 14
  • 20
  • Ok, I am going to edit my question. This is the one I've tried for the first time, but this doesn't work. I want to tell the compiler that I have an array of objects of NSObject type and all elements conform to Manager protocol. – Infinite Possibilities Jun 16 '15 at 08:23