2017-12-15 9 views
-1

SWIFT에서 JSON 및 Codable과 함께 작동하도록 일반 구조체를 만들려고 시도 중이지만 가능한 경우 알 수 없습니다.SWIFT 구조체의 Generics

제네릭없이 작동합니다.

struct apiContainer: Decodable { 
    let meta: Meta 
    let result: [Client] 
} 

"Client"라는 구조체가 있는데 다른 구조체 (예 : owner, plant)가 필요합니다.

모든 JSON 응답은 apiContainer로 이동해야합니다. 그것에는 Meta와 [Client]가 있습니다.

내 목표는 [Client]가 [T]가되도록하여 모든 구조체를 apiContainer에 전달할 수 있습니다.

벨로우는 놀이터에서 시도하는 코드 조각입니다.

질문 : 가능합니까? 내가 (구조체와 json.decode 라인에 모두)를 만들 수있는 방법

import PlaygroundSupport 
import UIKit 
import Foundation 


struct Client: Decodable { 
    let name: String 
    let postal_code: String 
    let city: String 
} 

struct Meta: Decodable { 
    let sucess: String 
    let value: String 
} 

struct apiContainer<T>: Decodable { 
    let meta: Meta 
    let result: [T] 
} 

let json = """ 
{ 
    "meta": { 
     "sucess": "yes", 
     "value": "123" 
    }, 
    "result": [ 
     { 
      "name": "Name 1", 
      "postal_code": "PC1", 
      "city": "City 1", 
      "address": "01 Street" 
     }, 
     { 
      "name": "Name 2", 
      "postal_code": "PC2", 
      "city": "City 2", 
      "address": "02 Street" 
     } 
    ] 
} 
""".data(using: .utf8)! 

let converted = try JSONDecoder().decode(apiContainer.self, from: json) 

print(converted.result) 
print(converted.meta) 

답변

1
struct apiContainer<T>: Decodable 

struct ApiContainer<T: Decodable>: Decodable 

그리고

try JSONDecoder().decode(apiContainer.self, from: json) 

될해야이어야한다

try JSONDecoder().decode(ApiContainer<Client>.self, from: json) 

그리고 voilà! 그것은 작동합니다.

+0

감사합니다. 그것은 효과가있다! 이제 IVE와 관련하여 또 다른 질문이 있습니다. https://stackoverflow.com/questions/47836787/passing-generics-to-function-call-and-getting-response-as-json –

+0

@RenanAguiar, upvoting 및 accepting 고려 이 대답은 그 때이다. – user28434