Hi I try to create enumerate()
method for my custom async array, but stil have compilation error. My Custom class looks like that:
class AsyncArray<T> {
private var array = [T]()
private var queue = DispatchQueue(label: "async_queue", attributes: .concurrent)
func enumerated() -> EnumeratedSequence<[T]> {
var value = EnumeratedSequence<[T]>() // compilation error Cannot invoke initializer for type 'EnumeratedSequence<[T]>' with no arguments
queue.sync {
value = self.array.enumerated()
}
return value
}
}
how can I implement enumerated()
method to my custom class?
You're assigning to value
only to immediately overwrite it in the sync
call. There's no need.
DispatchQueue.sync
lets you directly return a result:
import Dispatch
class AsyncArray<T> {
private var array = [T]()
private var queue = DispatchQueue(label: "async_queue", attributes: .concurrent)
func enumerated() -> EnumeratedSequence<[T]> {
return queue.sync {
return self.array.enumerated()
}
}
}
For reference: If you needed to assign to a captured variable, as you tried to do (which would be necessary an async
call, for example), it would look something like this:
import Dispatch
class AsyncArray<T> {
private var array = [T]()
private var queue = DispatchQueue(label: "async_queue", attributes: .concurrent)
func enumerated() -> EnumeratedSequence<[T]> {
var result: EnumeratedSequence<[T]>?
return someAsyncCall {
result = self.array.enumerated()
}
waitForAsyncCallToFinish()
return result!
}
}