如果Element符合给定协议,则扩展阵列以符合协议

kyl*_*ejm 8 protocols ios swift protocol-extension

我想做这样的事情,但无法正确使用语法或在网络上的任何地方找到正确的方法来编写它:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我只想在这个数组的元素符合时才符合Array我的协议.JSONDecodeableJSONCollectionElement

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

Nat*_*ook 5

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


the*_*end 1

斯威夫特 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
    }
}
Run Code Online (Sandbox Code Playgroud)