gpt4 book ai didi

swift - 传入 runtimeType 作为泛型函数参数

转载 作者:行者123 更新时间:2023-11-28 07:48:27 30 4
gpt4 key购买 nike

我是一名 Swift 开发人员,也是 Dart 的新手。我正在尝试编写一些通用方法。

我想知道我是否可以在 Dart 中实现类似的事情。

//Swift version

public func modelFrom<T: Mappable>(response: Encodable?, model: T.Type) -> T? {

if let response = response, let string = response.jsonString {
return T(JSONString: string)
}

return nil

}

// The method can be called like this

let responseModel = modelFrom(response: response, model: FoodLogModel.self)

对于 Dart,我可以转换泛型类的类型吗?喜欢<T: Mappable>在 swift ?

runtimeType在 Dart 中相当于 <ClassName>.self在 Swift 中?

非常感谢

这是我试过的,

import 'package:dartson/dartson.dart';
import 'package:mobile_corelib/base/model.dart';

T requestFrom<T>(BaseModel model, Type T) {

try {

var dson = new Dartson.JSON();
var object = dson.map(dson.encode(model), T.runtimeType);

return object;
} catch(error) {
return null;
}
}
var dick = requestFrom(model, AccessTokenRequest().runtimeType)

但是我不知道如何传入Class type .我应该使用 dynamic 吗? ?或 Type

最佳答案

runtimeType在 Dart 中是 Type 类型的值,这与在泛型类型参数中编写类型时发生的情况不同。

例如,new List<String>()有效,但是 new List<''.runtimeType>()是语法错误。

一般来说,Type是相当有限的。您不能使用它来创建新实例——除非您在 VM 中,您可以在其中使用镜像。

关于swift - 传入 runtimeType 作为泛型函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50326435/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com