swift - NSObject 类符合 Swift 中 NSArray 中包含的协议(protocol)

标签 swift nsarray protocols swift2 swift-array

我想在 Swift 中创建一个方法,它返回符合协议(protocol)的 NSObject 对象数组。 我尝试过这样的事情:

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 是一个协议(protocol)。我收到错误消息,指出 return 语句中的转换始终会失败。
我想告诉编译器我有一个 NSObject 类型的对象数组,并且所有元素都符合 Manager 协议(protocol)。

最佳答案

不要尝试用 Swift 编写 Objective-C。远离 NSObjectNSArrayNSMutableArray

这是您的代码,没有任何 Objective-C 类型:

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

如果你想确保你的返回类型是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
}

关于swift - NSObject 类符合 Swift 中 NSArray 中包含的协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30862165/

相关文章:

ios - 使用 AWS Appsync 将图像上传到 s3 的过程 ||使用 Appsync 上传 iOS 图片

swift - UICollectionView 单元格为零

Swift:无法为 'Array<Character>' 类型的值添加下标

ios - 如何将数组中的json值赋给字典?

ios - 转换为 swift 3 后, View Controller 中出现奇怪的通用函数

ios - 在 Swift 中更新 Parse currentUser() 的缓存副本

xcode - Swift:如何将协议(protocol)类型转换为特定协议(protocol)?

cocoa - 避免协议(protocol)方法找不到方法

ios - Objective-C 中的 BOOL 数组

swift - 带有 Swift 协议(protocol)的通用类