【问题标题】:How can I "cast" a type to a type that conforms to a protocol?如何将类型“强制转换”为符合协议的类型?
【发布时间】:2020-06-24 05:37:52
【问题描述】:

如果我有一个对其类型有协议要求的泛型函数,例如

func decodeDecodable<DataModel: Decodable>(ofType dataModelType: DataModel.Type, from data: Data) throws -> DataModel {
  return try JSONDecoder().decode(dataModelType, from: data)
}

如何从可能符合或可能符合协议的泛型类型调用它?

// The generic DataModel can be anything
func decode<DataModel>(ofType dataModelType: DataModel.Type, from data: Data) throws -> DataModel {
  if let decodableType = dataModelType as? Decodable { // <--- what would this be?
    return try decodeDecodable(ofType: decodableType, from: data)
  } else {
    ...
  }
}

【问题讨论】:

  • 您不能将值强制转换为类型并将其传递给具有泛型参数的方法。 decodeDecodable 的 DataModel 类型必须符合 Decodable 并且该类型必须在编译时已知。
  • 为什么要这样做?如果类型是可解码的,您是否尝试以一种方式解码数据,如果不是,则以另一种方式解码?那为什么不直接写同一个方法的两个重载呢?
  • 是的,我想我必须这样做。我想知道是否还有其他方法

标签: swift generics casting


【解决方案1】:

这种方法应该有效

 if let decodableType = dataModelType.self as? Decodable.Type {
        //  conform Protocol
    } else {
    //
    }

if dataModelType.self is Decodable.Type {
    //  conform Protocol
} else {
//
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多