通用异步数组的enumerate()方法

时间:2018-07-05 17:30:42

标签: arrays swift generics dispatch

嗨,我尝试为我的自定义异步数组创建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()方法?

1 个答案:

答案 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!
    }
}