2017-03-26 128 views
0

我要調用的方法是這樣的:斯威夫特 - 由泛型類型初始化類協議

createModel(Model.Type, json) 

功能應該調用構造函數的參數給定類型。構造函數在協議中定義(來自ObjectMapper)。我不熟悉swift中的泛型類型。這是我迄今爲止的,但它不起作用。

func createModel<T: Mappable>(model: T.Type, json: JSON){ 
    return model(JSON: json) 
} 
+0

你缺少的返回類型(即加上' - > T'給你的函數)。 –

回答

2

在這裏,我已經在註釋中描述它。您的代碼中有一些情況是您可以互換使用JSON和json。在代碼中,我使用JSON將類型別名和json標識爲變量名稱。此外,在斯威夫特的格式是varName: type當在參數列表

typealias JSON = [String: Any] // Assuming you have something like this 

// Assuming you have this 
protocol Mappable { 
    init(json: JSON) // format = init(nameOfVariable: typeOfVariable) 
} 

class Model: Mappable { 
    required init(json: JSON) { 
     print("a") // actually initialize it here 
    } 
} 

func createModel<T: Mappable>(model: T.Type, json: JSON) -> T { 
    // Initializing from a meta-type (in this case T.Type that we int know) must explicitly use init. 
    return model.init(json: json) // the return type must be T also 
} 

// use .self to get the Model.Type 
createModel(model: Model.self, json: ["text": 2]) 
+0

工程就像一個魅力。謝謝 –

相關問題