我在我的应用程序中使用 NSOperationQueue,我用 Objective C 编写它。我目前正在将我的应用程序转换为 Swift。我想知道如何使用 NSOperationQueue 在 Swift 中?
这是我在 objective-c 上的代码
-(NSOperationQueue*)operationQueue
{
if(_operationQueue == nil) {
_operationQueue = [NSOperationQueue new];
}
return _operationQueue;
}
而且我已经尝试过 swift
func operationQueue() -> NSOperationQueue{
if(_operationQueue == nil){
_operationQueue = NSOperationQueue.new()
}
}
但它给我错误:
NSOperationQueue is not convertible to 'MirrorDispotion'
请您参考如下方法:
Objective-C 代码使用operationQueue 方法(或属性) 加上 _operationQueue 实例变量用于“按需 初始化”。相应的 Swift 3 代码将是 (对于旧版本,将 OperationQueue 替换为 NSOperationQueue):
class MyClass {
var _operationQueue: OperationQueue?
func operationQueue() -> OperationQueue {
if _operationQueue == nil {
_operationQueue = OperationQueue()
}
return _operationQueue!
}
// ...
}
代码中的主要错误是 _operationQueue 不是 已定义,并且该函数不返回值。
但是在 Swift 中使用“惰性存储属性”可以更容易地实现同样的目标:
class MyClass {
lazy var operationQueue = OperationQueue()
// ...
}
当使用该属性时,该值将仅计算一次 第一次:
let mc = MyClass()
print(mc.operationQueue) // operation queue is created and returned
print(mc.operationQueue) // same operation queue is returned
参见 "Properties" 中的“惰性存储属性”在 Swift 文档中 获取更多信息。
