NSObject class conforms to protocol contained in NSArray with Swift

739 views Asked by At

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.

2

There are 2 answers

2
vrwim On BEST ANSWER

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
}
1
lammert On

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) }
}