Swift 泛型从数组中删除类实例

标签 swift swift3

我想实现以下目标;能够从数组中删除任何给定的实例。然而,以下是无效的 Swift 3 语法:

extension Array where Element: class { // error: Expected identifier for type name
    mutating func remove(_ object: AnyObject) {
        if let index = index(where: { $0 === object }) {
            remove(at: index)
        }
    }
}

protocol MyProtocol: class { }
class MyClass: MyProtocol { }
var myInstance = MyClass()
var myArray: [MyProtocol] = [myInstance]
myArray.remove(myInstance)

通用方法如何运作?我不想对 MyProtocol 或 Equatable 的通用扩展进行特殊处理。

最佳答案

将您的限制转换为 AnyObject 而不是 class:

extension Array where Element: AnyObject {
    mutating func remove(_ object: Element) {
        if let index = firstIndex(where: { $0 === object }) {
            remove(at: index)
        }
    }
}

以下注释不再正确,保留它们以供历史引用。

现在唯一的问题是编译器不允许您声明 var myArray: [MyProtocol],因为它会抛出以下内容:

error: using 'MyProtocol' as a concrete type conforming to protocol 'AnyObject' is not supported

因此您需要var myArray: [AnyObject]Here很好地解释了为什么当前 Swift 中存在此限制。

关于Swift 泛型从数组中删除类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39578871/

相关文章:

xcode - Mac OS X SpriteKit 的替代品

arrays - 字符串数组相等性的 Swift 字典

ios - 数据未显示在标签中

regex - 来自 URL 的 Youtube 视频 ID - Swift3

swift - 成功传递数据时应用程序崩溃

swift - 在 Firebase 中删除项目

ios - 委派设置后未出现导航栏

ios - 指定 CKDatabaseSubscription 的谓词和选项

ios - Swift - 从一年中的某一天获取日期

ios - 在 ScrollView 中创建一个列表