【问题标题】:Make array type from type从类型创建数组类型
【发布时间】:2018-05-04 17:47:54
【问题描述】:

我正在从我的服务器获取大量数据。

要序列化它,我使用ModelMapper。我有很多Mappable 对象,所以我需要一个能够映射任何类型的可映射数据的函数。像这样的:

func serializeData(of type: Mappable.Type) -> [Mappable]? {
     return try? response?.map(to: [type].self)
}

我的问题是 map(:) 方法需要 [Mappable].Type 作为输入。 [type].self 然而是[Mappable.Type]。我在这里迷路了。请帮忙

【问题讨论】:

    标签: swift types casting


    【解决方案1】:

    将类型传递为foo.Type 是一种非常objective-c-ish 的模式。

    在 Swift 中,我更喜欢通用解决方案,例如

    func serializeData<T : Mappable>() -> [T]? {
         return try? response?.map(to: [T].self)
    }
    

    还是更快捷

    func serializeData<T : Mappable>() throws -> [T] {
         return try response?.map(to: [T].self) ?? []
    }
    

    【讨论】:

    • 我总是对您的回复印象深刻。你有 Swift 博客或类似的东西吗?
    • @D.Greg 谢谢。不,我没有。
    猜你喜欢
    • 2022-06-22
    • 1970-01-01
    • 2021-12-09
    • 2019-05-19
    • 2011-10-27
    • 1970-01-01
    • 2021-09-27
    • 2021-09-29
    • 2012-05-30
    相关资源
    最近更新 更多