[英]Array requires that 'Element' conform to 'Equatable'
I am writing an iOS App in Swift.我正在 Swift 中编写一个 iOS 应用程序。 I added a class SynchronizedArray .我添加了一个 class SynchronizedArray 。 On its remove method I am getting an error:在它的删除方法上,我收到一个错误:
Referencing instance method 'remove(obj:)' on 'Array' requires that 'Element' conform to 'Equatable'在 'Array' 上引用实例方法 'remove(obj:)' 要求 'Element' 符合 'Equatable'
I tried the solutions on the internet but not working.我尝试了互联网上的解决方案,但没有奏效。
Code:代码:
final class SynchronizedArray<Element> {
var array: [Element]
private let queue: DispatchQueue
func remove(_ element:Element){
queue.async(flags: .barrier) {
self.array.remove(obj:element)
//Error: Referencing instance method 'remove(obj:)' on 'Array' requires that 'Element' conform to 'Equatable'
}
}
}
fileprivate extension Array where Element: Equatable {
// Remove first collection element that is equal to the given `object`:
mutating func remove(obj: Element) {
if let index = index(of: obj) {
remove(at: index)
}
}
}
Your class should conform to Equatable
and index(of:)
is deprecated use firstIndex
您的 class 应符合Equatable
和index(of:)
已弃用使用firstIndex
final class SynchronizedArray<Element:Equatable> {
var array: [Element] = []
private let queue: DispatchQueue? = nil
func remove(_ element:Element){
queue?.async(flags: .barrier) {
self.array.remove(obj:element)
//Error: Referencing instance method 'remove(obj:)' on 'Array' requires that 'Element' conform to 'Equatable'
}
}
}
fileprivate extension Array where Element: Equatable {
// Remove first collection element that is equal to the given `object`:
mutating func remove(obj: Element) {
if let index = firstIndex(of: obj) {
remove(at: index)
}
}
}
Simply modify the class SynchronizedArray
declaration and conform Element
to Equatable
like so,只需修改class SynchronizedArray
声明并将Element
与Equatable
一致,如下所示,
final class SynchronizedArray<Element: Equatable> {
//rest of the code...
}
This will resolve your initial issue.这将解决您最初的问题。
Another issue will the pop up saying Class 'SynchronizedArray' has no initializers .另一个问题会弹出说Class 'SynchronizedArray' has no initializers 。 That's because you haven't initialised the stored properties of the class
.那是因为您尚未初始化class
的存储属性。 Use below code when defining the properties,定义属性时使用下面的代码,
var array = [Element]()
private let queue = DispatchQueue.main //Initialize with whatever type of queue you want to use
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.