我想实现以下目标;能够从数组中删除任何给定的实例。然而,以下是无效的 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/