无法在 Swift 中延长关闭时间?

Can't extend closure in Swift?

由于扩展 Bool 而兴奋不已,我认为在 Swift 中扩展闭包会很有趣(我们在 Smalltalk 中毫不费力地做到了这一点,所以为什么不呢?)。 =16=]

这是我的游乐场:

typealias NiladicClosure = () -> ()

extension NiladicClosure {
    var theAnswerToLife:Int {
        return 42
    }
}

let block:NiladicClosure = {}

block.theAnswerToLife

不行,说NiladicClosure does not have a member named '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 {
^         ~~~~~~~~~~~~~~

什么是 non-nominal type?有没有pattern/workaround?

早于 Swift 2 的其他类似问题也足够具体,以至于人们为特定扩展提供了解决方法。我感兴趣的是 Swift 闭包是否是我可以添加额外行为的第一个 class 对象,就像 Swift.

中的其他东西一样

What is a non-nominal type?

A nominal type 是一种具有显式名称的类型。非标称类型是没有名称的类型,例如 () -> ()。不能扩展复合类型,包括闭包和元组(例如 (Int, String))。

Is there a pattern/workaround?

您可以使用组合而不是扩展,也许使用 Swift 2 的新协议功能:

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