swift - 无法在 Swift 中扩展闭包?

标签 swift closures swift2

因为扩展 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/

相关文章:

ios - Swift - 从 Alamofire POST 请求中获取数据

ios - 如何防止 dequeueReusableCellWithIdentifier 重复我的段选择?

java - 在 swift 中转义闭包以及如何在 Java 中执行它

methods - 如何从方法的闭包中删除强引用循环?

ios - 在 Collection View Controller 中快速创建两个 View

swift - 用户如何将其图表请求的个人资料图像更改为相册中的图像

iOS 11 禁用密码自动填充附件 View 选项?

ios - Firebase addStateDidChangeListener

Javascript 闭包函数参数?

xcode - 在 Swift 中将图像从 .write 恢复到文件