要将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]

swift model 转换成StringAny

原文地址: https://www.cveoy.top/t/topic/iUmH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录