无法在Swift中延长关闭?

时间:2015-06-18 21:34:07

标签: swift closures swift2

从扩展Bool中感到兴奋,我认为在Swift中扩展闭包会很有趣(我们在Smalltalk中完全不做任何事情,为什么不呢?)。

这是我的游乐场:

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?有模式/解决方法吗?

其他类似的问题早于Swift 2,也足够具体,人们为特定的扩展提供了变通方法。我对Swift闭包是否是可以添加其他行为的第一类对象感兴趣,就像Swift中的其他东西一样。

1 个答案:

答案 0 :(得分:8)

  

什么是非名义类型?

nominal type是具有显式名称的类型。非名义类型是没有这种名称的类型,如() -> ()。无法扩展复合类型,包括闭包和元组(例如(Int, String))。

  

是否有模式/解决方法?

您可以使用合成而不是扩展,也许使用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
相关问题