Swift 模型转换为字典 [String:Any] 的方法
要将 Swift 模型转换为 [String:Any],您可以使用 Swift 的反射功能(Reflect)来遍历模型的属性,并将其转换为键值对。下面是一个示例代码:
func convertModelToDictionary<T: Codable>(model: T) -> [String: Any]? {
let mirror = Mirror(reflecting: model)
var dictionary = [String: Any]()
for child in mirror.children {
if let label = child.label {
dictionary[label] = child.value
}
}
return dictionary
}
您可以将上述函数调用,将 Swift 模型转换为 [String:Any],如下所示:
struct Person: Codable {
var name: String
var age: Int
}
let person = Person(name: 'John', age: 30)
let dictionary = convertModelToDictionary(model: person)
print(dictionary)
输出结果将是一个包含模型属性和值的字典:
['name': 'John', 'age': 30]
请注意,上述代码仅适用于 Swift 4 及更高版本,并且模型必须遵循 Codable 协议。如果您的模型不遵循 Codable 协议,您可以使用其他方式来获取模型的属性并将其转换为 [String:Any]。
原文地址: https://www.cveoy.top/t/topic/qAl0 著作权归作者所有。请勿转载和采集!