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
这可能吗?如果是这样,语法是什么?
斯威夫特 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)