【问题标题】:Extend Array to conform to protocol if Element conforms to given protocol如果 Element 符合给定协议,则扩展 Array 以符合协议
【发布时间】:2015-10-19 16:22:47
【问题描述】:

我想做这样的事情,但无法获得正确的语法或在网络上找到任何提供正确编写方式的地方:

protocol JSONDecodeable {
    static func withJSON(json: NSDictionary) -> Self?
}

protocol JSONCollectionElement: JSONDecodeable {
    static var key: String { get }
}

extension Array: JSONDecodeable where Element: JSONCollectionElement {
    static func withJSON(json: NSDictionary) -> Array? {
        var array: [Element]?
        if let elementJSON = json[Element.key] as? [NSDictionary] {
            array = [Element]()
            for dict in elementJSON {
                if let element = Element.withJSON(dict) {
                    array?.append(element)
                }
            }
        }
        return array
    }
}

所以我想仅当此数组的元素符合JSONCollectionElement 时,才使Array 符合我的协议JSONDecodeable

这可能吗?如果有,语法是什么?

【问题讨论】:

  • 使用像 Array 这样的泛型

标签: ios swift protocols protocol-extension


【解决方案1】:

这在 Swift 中是不可能的。您可以在标准库中看到同样的情况:Array 在使用 Equatable 元素声明时不会获得 Equatable 一致性。

【讨论】:

  • @OrkhanAlikhanov 仍然不可能。我从 XCode 收到 Extension of type 'Array' with constraints cannot have an inheritance clause 构建时间错误。
【解决方案2】:

斯威夫特 4.2

在 Swift 4.2 中,我能够使用符合如下协议的元素扩展数组:

public extension Array where Element: CustomStringConvertible{
    public var customDescription: String{
        var description = ""
        for element in self{
            description += element.description + "\n"
        }

        return description
    }
}

【讨论】:

  • 确认!谢谢!我快速浏览了有关 Swift 4.2 中此更改的一些信息,但找不到任何信息。如果有人知道,请分享!
  • 对于可选数组?元素必须符合某些协议的地方
【解决方案3】:

我建议使用包装器。比如

struct ArrayContainer<T: Decodable>: Container {
    let array: [T]
}

【讨论】:

    【解决方案4】:

    我不知道这是否是最好的方法,或者苹果是否打算以这种方式使用它。我用过一次,对我来说效果很好:

    假设你有以下协议

    protocol MyProtocol {
        var test: Bool { get }
    }
    

    您可以对数组执行此操作

    extension Array: MyProtocol where Element: MyProtocol {
        var test: Bool {
            return self.allSatisfy({ $0.test })
        }
    }
    

    这是字典

    extension Dictionary: MyProtocol where Value: MyProtocol {
        var test: Bool {
            return self.values.allSatisfy({ $0.test })
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      相关资源
      最近更新 更多