9

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

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
    }
}

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

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

4

4 回答 4

5

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

于 2015-10-19T18:19:46.927 回答
1

我建议使用包装器。例如

struct ArrayContainer<T: Decodable>: Container {
    let array: [T]
}
于 2018-01-19T10:06:59.150 回答
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
    }
}
于 2018-10-21T18:15:52.890 回答
0

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

假设您有以下协议

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 })
    }
}
于 2018-12-01T17:47:18.090 回答