因为扩展 Bool
而兴奋不已,我认为在 Swift 中扩展闭包会很有趣(我们在 Smalltalk 中毫不费力地做到了这一点,为什么不呢?)。
这是我的 Playground :
typealias NiladicClosure = () -> ()
extension NiladicClosure {
var theAnswerToLife:Int {
return 42
}
}
let block:NiladicClosure = {}
block.theAnswerToLife
它不起作用,表示 NiladicClosure 没有名为“theAnswerToLife”的成员
。查看控制台,我得到了更多信息:
Playground execution failed: /var/folders/2k/6y8rslzn1m95gjpg534j7v8jzr03tz/T/./lldb/33726/playground119.swift:3:1: error: non-nominal type 'NiladicClosure' cannot be extended
extension NiladicClosure {
^ ~~~~~~~~~~~~~~
什么是非标称类型
?有模式/解决方法吗?
早于 Swift 2 的其他类似问题也非常具体,以至于人们为特定扩展提供了解决方法。我感兴趣的是 Swift 闭包是否是我可以添加额外行为的一流对象,就像 Swift 中的其他东西一样。
最佳答案
What is a non-nominal type?
A nominal type是具有显式名称的类型。非标称类型是没有名称的类型,例如 () -> ()
。无法扩展复合类型,包括闭包和元组(例如 (Int, String)
)。
Is there a pattern/workaround?
您可以使用组合而不是扩展,或许可以使用 Swift 2 的新协议(protocol)功能:
typealias NiladicClosure = () -> ()
protocol NiladicClosureProtocol {
var someClosure : NiladicClosure? {get}
}
protocol SorryForTheInconvenience {
var theAnswerToLife : Int {get}
}
extension SorryForTheInconvenience {
var theAnswerToLife : Int {
return 42
}
}
struct SomethingAwesome : NiladicClosureProtocol, SorryForTheInconvenience {
var someClosure : NiladicClosure?
}
let foo = SomethingAwesome()
foo.theAnswerToLife // 42
关于swift - 无法在 Swift 中扩展闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30926186/