【问题标题】:Extension for Array with Closures带闭包的数组扩展
【发布时间】:2019-06-16 18:35:57
【问题描述】:

我有一个包含闭包的数组,其中包含下一种类型的闭包:

typealias FuncT = (()->Void)

我想为包含我的函数的数组添加扩展方法:

extension Array where Element : FuncT {
    func execAll() {
        self.forEach { (f) in
            f()
        }
    }
}

我得到编译错误:

类型“元素”被限制为非协议、非类类型“FuncT” (又名'() -> ()')

如何向包含我的函数的数组添加方法?

【问题讨论】:

    标签: arrays swift closures extension-methods


    【解决方案1】:

    约束where A : BA 限制为 B 的子类,或符合协议 B 的类型。函数类型是值类型而不是类,不能符合协议。

    您需要的是“相同类型的要求”where A == B。在你的情况下:

    extension Array where Element == FuncT { ... }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-02
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多