嗨,我尝试为我的自定义异步数组创建enumerate()
方法,但是stil出现编译错误。我的自定义类如下:
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
}
}
如何为自定义类实现enumerated()
方法?
答案 0 :(得分:1)
您要分配给value
只是为了在sync
调用中立即覆盖它。没必要。
DispatchQueue.sync
可让您直接返回结果:
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()
}
}
}
供参考:如果需要像尝试做的那样分配给捕获的变量(例如,必须进行async
调用),它看起来像这样:
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!
}
}