Tôi muốn làm điều gì đó như thế này, nhưng không thể tìm đúng cú pháp hoặc tìm bất kỳ đâu trên web cung cấp đúng cách để viết nó:Mở rộng mảng để phù hợp với giao thức nếu Phần tử tuân theo giao thức đã cho
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
}
}
Vì vậy, tôi muốn tuân thủ Array
đối với giao thức của tôi JSONDecodeable
chỉ khi các thành phần của mảng này tuân theo JSONCollectionElement
.
Điều này có khả thi không? Nếu vậy, cú pháp là gì?
Sử dụng Generics giống như Array –