2015-10-08 4 views
21

In swift 2 Voglio estendere il tipo di array. Ho un protocollo JSONDecodable. Quello che voglio dire al compilatore è conforme allo Array al protocollo JSONDecodable se gli elementi di Array sono anche JSONDecodable. Ecco il codice:L'estensione del tipo Array con vincoli non può avere una clausola di ereditarietà - swift 2

public protocol JSONDecodable { 
    static func createFromJSON(json: [String: AnyObject]) throws -> Self 
} 

extension Array: JSONDecodable where Element: JSONDecodable { 

} 

Ma compilatore dà l'errore: "Estensione di tipo Array con i vincoli non può avere una clausola di eredità"

Quindi c'è qualche altro modo per ottenere questo tipo di comportamento?

+0

ho trovato this..twitter.com/jadengeller/status/644735717814349824 Qualche idea su cosa intenda per "scrivere una struttura wrapper"? – Austin

risposta

0

Penso the hint che hai trovato su Twitter significa qualcosa di simile:

protocol X { 
    var xxx: String { get } 
} 

// This is a wrapper struct 
struct XArray: X { 

    let array: Array<X> 

    var xxx: String { 
     return "[\(array.map({ $0.xxx }).joinWithSeparator(", "))]" 
    } 

} 

// Just for this demo 
extension String: X { 
    var xxx: String { 
     return "x\(self)" 
    } 
} 

let xs = XArray(array: ["a", "b", "c"]) 
print(xs.array) // ["a", "b", "c"] 
print(xs.xxx) // [xa, xb, xc] 
7

come su piccolo tipo la cancellazione? Si dovrebbe fare il segno di spunta

protocol JSONDecodable { 
    init(json: JSON) throws 
} 

Mentre Swift 3 non permette fare come estensione

extension Array: JSONDecodable where Element: JSONDecodable 

ma la sua possibile fare:

extension Array: JSONDecodable { 
    init(json: JSON) throws { 
     guard let jsonArray = json.array, 
      let decodable = Element.self as? JSONDecodable.Type else { 
       throw JSONDecodableError.undecodable 
     } 

     self = jsonArray.flatMap { json in 
      let result: Element? = (try? decodable.init(json: json)) as? Element 
      return result 
     } 
    } 
} 
+0

Questo dovrebbe essere contrassegnato come risposta. – bubuxu