gpt4 book ai didi

ios - 将 nil 传递给具有泛型类型约束的可选参数的编译错误

转载 作者:行者123 更新时间:2023-11-28 06:49:57 25 4
gpt4 key购买 nike

我的类 MQChainedOperation 有一个函数 append,它接受从 MQOperation 继承的任何操作:

public func append<T: MQOperation>(operation: T, 
validator: (Any? -> Bool)?,
configurator: ((T, Any?) -> Void)?) {
// ...
}

在 View Controller 中,我这样做:

let chain = MQChainedOperation()
chain.append(
MQBlockOperation {[unowned self] in
// ...
},
validator: nil,
configurator: nil)
chain.append(
SignUpOperation(),
validator: nil,
configurator: nil)

MQBlockOperationSignUpOperation 都继承自 MQOperation 时,编译器从两次追加调用中向我抛出此错误:

Cannot invoke 'append' with an argument list of type '(MQOperation, validator: (Any? -> Bool)?, configurator: ((MQOperation, Any?) -> Void)?)'

Expected an argument list of type '(T, validator: (Any? -> Bool)?, configurator: ((T, Any?) -> Void)?)'

但是,如果我为 configurator 提供一个空的闭包,它会起作用:

chain.append(
MQBlockOperation {[unowned self] in
// ...
return NSDate()
},
validator: nil,
configurator: {(op, result) in})
chain.append(
SignUpOperation(),
validator: nil,
configurator: {(op, result) in})

我应该能够将 nil 传递给可选参数,而解决方法使我的代码变得丑陋。我该如何解决这个问题?

最佳答案

如评论中所述,这似乎是 Swift 编译器的错误。目前,我喜欢的一种快速、干净的修复方法是提供 nil 作为函数签名中的默认值。

public func append<T: MQOperation>(operation: T,
validator: (Any? -> Bool)?,
configurator: ((T, Any?) -> Void)? = nil)

关于ios - 将 nil 传递给具有泛型类型约束的可选参数的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35196999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com