我想要做這樣的事情,但無法獲得正確的語法或在網絡上的任何地方找到正確的寫法:如果元素符合給定的協議,擴展數組以符合協議
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
。
這可能嗎?如果是這樣,語法是什麼?
使用泛型像陣 –