json - 如何在 Swift 中将类作为参数传递
问题描述
在java中,我们可以做到这一点
public Object setClass(String JSONString, Class clazz){
return JSON.parseObject(JSONString,clazz)
}
但是在 Swift 中,我应该怎么做才能将类作为参数传递。就像
public func decodeData(dataValue : Data, decodeClass: AnyClass){
do {
let json = try JSONDecoder().decode(decodeClass, from: dataValue)
let resultData = json.info;
}catch{
}
}
解决方案
您将需要在此处使用泛型:
func decode<T: Decodable>(data: Data, type: T.Type){
do {
let json = try JSONDecoder().decode(type, from: data)
} catch {
//
}
}
当你想打电话时,你可以使用.self
符号:
decode(data: data, type: String.self)
decode(data: data, type: [String].self)
decode(data: data, type: [Int].self)
推荐阅读
- swiftui - SwiftUI DragGesture 只在一个方向
- python - 从 Python 代码(正则表达式或 AST)字符串中提取所有变量
- lisp - 我是 lisp 的初学者。如何在 LISP 中为 R 关系创建传递函数?
- c# - 在 MvvmCross 中使用“标准”ChangePresentation Hints 时,使用“返回”导航导航到新 ViewModel 的方法是什么?
- rust - 我可以在不包装浮点类型和滥用 BTreeMap 的情况下使用标准库执行二叉树搜索吗?
- python - 如何在 databricks 工作区中使用 python 获取 azure datalake 存储中存在的每个文件的最后修改时间?
- azure - Azure Functions:如何在 Azure 存储队列的绑定表达式中使用 POCO?
- flutter - 选择 TextField 或 TextFormField 时 Flutter 应用程序冻结
- reactjs - 为会员页面设置状态授权时的安全风险
- string - 第 1 阶段引导加载程序打印字符串