2017-10-26 12 views
1

私は再利用したい機能があり、Decocable構造体のパラメータを受け入れる必要があります。たとえば、これは私の現在のコードを簡略化したものである(「MyDecodableStructは」復号可能な構造体は、アプリ内の他の場所で宣言されていると仮定):Swift 4で一般的なDecodable構造体を参照する方法

static func getResults(url: String, parameters: Parameters) { 
    // On success REST response 
    if response.result.isSuccess { 
     struct Results: Decodable { 
      let items: [MyDecodableStruct] 
     } 

     if let jsonResults = try? JSONDecoder().decode(Results.self, from: response.data!) { 
     //success 
    } 
} 

、代わりの「MyDecodableStructを」と言って、私はそれがどの復号可能になりたいですstruct私はパラメータとして渡します。このような何か:

static func getResults(url: String, parameters: Parameters, myStruct: Decodable) { 
    // On success REST response 
    if response.result.isSuccess { 
     struct Results: Decodable { 
      let items: [myStruct] 
     } 

     if let jsonResults = try? JSONDecoder().decode(Results.self, from: response.data!) { 
     //success 
    } 
} 

と私は、これはしかし動作するように取得する方法についての構文を把握することはできません

getResults(url: "url", parameters: nil, myStruct: MyDecodableStruct) 

のようにそれを呼び出します。私が得るエラーは

Type 'Results' does not conform to protocol 'Decodable' 
Expected element type 

これを処理するための最良の方法はありますか?

答えて

3

型をパラメーターとして渡す場合は、パラメーターの型をメタタイプと宣言する必要があります。あなたの場合、それはDecodableに従う必要がある一般的なタイプです。

ですから、このような何かを書く必要があります。

struct Results<Element: Decodable>: Decodable { 
    let items: [Element] 
} 
static func getResults<Element: Decodable>(url: String, parameters: Parameters?, myStruct: Element.Type) { 
    //... 
     // On success REST response 
     if response.result.isSuccess { 

      do { 
       let jsonResults = try JSONDecoder().decode(Results<Element>.self, from: response.data!) 
       //success 
       print(jsonResults) 
      } catch { 
       //Better not dispose errors silently 
       print(error) 
      } 
     } 
    //... 
} 

スウィフトはタイプが一般的なコンテキストで入れ子にすることができないと言うので、私は外側の非ジェネリックコンテキストにそれを移動しました。おかげで、非常に役に立っ

getResults(url: "url", parameters: nil, myStruct: MyDecodableStruct.self) 
+0

は、としてそれを呼び出します! –

関連する問題