我可以在Swift的typealias中添加泛型类型吗?

时间:2017-08-08 02:24:48

标签: swift generics

我有$(document).ready(function(){ $('.bxslider').bxSlider({ auto: true, autoControls: true minSlides: 3, maxSlides: 9, slideWidth: 170, slideMargin: 10, ticker: false, //true speed: 20000 }); }); 来自网络电话回拨。

var component = react_test_renderer_1["default"].create(<jumbotron_1["default"] />);
                                                        ^

    SyntaxError: Unexpected token <

但后来我意识到有时我也需要:

typealias

我可以使用某种通用语法简化此typealias GenericReturn = ((Bool, Int, GenericModel)->Void); 吗?可能就像:

typealias UserReturn = ((Bool, Int, UserModel)->Void);
typealias PriceReturn = ((Bool, Int, PriceModel)->Void);
typealias ClientReturn = ((Bool, Int, ClientModel)->Void);
typealias ProductReturn = ((Bool, Int, ProductModel)->Void);
typealias CartReturn = ((Bool, Int, CartModel)->Void);

感谢。

1 个答案:

答案 0 :(得分:0)

您可以将以下代码用作通用类型别名

typealias MapResult<T> = (_ result: () throws -> T) -> Void

并在您的代码中使用它来映射网络结果,如下所示:

func getSomeData(completion: @escaping MapResult<YourModel>) {
    let url = "Some Url"
    network.get(from: url) { (inner) in
        do {
            let result = try inner()
            let model: YourModel = try mapObject(result) 
            completion { return YourModel }
        } catch let error {
            completion { throw error}
        }
    }
}

和mapObject基于你反序列化结果的方式,我使用Marshal将是这样的:

func mapObject<T: Unmarshaling>(_ data: Data) throws -> T {
    return try T(object: try JSONParser.JSONObjectWithData(data))
}

和映射数组:

func mapArray<T: Unmarshaling>(_ data: Data) throws -> [T] {
    return try JSONParser.JSONArrayWithData(data).map(T.init)
}