Swift “我怎么能?”;铸造;将类型转换为符合协议的类型?
如果我有一个对其类型有协议要求的泛型函数,比如Swift “我怎么能?”;铸造;将类型转换为符合协议的类型?,swift,generics,casting,Swift,Generics,Casting,如果我有一个对其类型有协议要求的泛型函数,比如 func decodeDecodable<DataModel: Decodable>(ofType dataModelType: DataModel.Type, from data: Data) throws -> DataModel { return try JSONDecoder().decode(dataModelType, from: data) } func decodeDecodable(ofType dataM
func decodeDecodable<DataModel: Decodable>(ofType dataModelType: DataModel.Type, from data: Data) throws -> DataModel {
return try JSONDecoder().decode(dataModelType, from: data)
}
func decodeDecodable(ofType dataModelType:DataModel.Type,from data:data)抛出->数据模型{
返回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 {
...
}
}
//通用数据模型可以是任何类型
func decode(of Type dataModelType:DataModel.Type,from data:data)抛出->数据模型{
如果让decodableType=dataModelType为?Decodable{/,这种方法应该可以工作
if let decodableType = dataModelType.self as? Decodable.Type {
// conform Protocol
} else {
//
}
或
您不能将值强制转换为类型并将其传递给具有泛型参数的方法。decodedecondable
的数据模型类型必须符合Decodable,并且该类型必须在编译时已知。为什么要这样做?如果该类型是可解码的,您是否尝试以一种方式对数据进行解码,如果该类型不可解码,则以另一种方式对数据进行解码?为什么不编写两个ov那么相同方法的工作量呢?是的,我想我必须这样做。我想知道是否还有其他方法
if dataModelType.self is Decodable.Type {
// conform Protocol
} else {
//
}