swift结构体转字典方式

在 Swift 中,将结构体转换为字典可以通过几种方法实现。以下是常见的实现方式:

使用 Codable 协议

结构体遵循 Codable 协议,利用 JSONEncoderJSONDecoder 进行转换:

struct Person: Codable {
    var name: String
    var age: Int
}

let person = Person(name: "Alice", age: 30)
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(person),
   let dictionary = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any] {
    print(dictionary) // ["name": "Alice", "age": 30]
}

手动转换为字典

通过扩展结构体,自定义 toDictionary 方法:

extension Person {
    func toDictionary() -> [String: Any] {
        return ["name": name, "age": age]
    }
}

let dict = person.toDictionary()
print(dict) // ["name": "Alice", "age": 30]

使用反射(Mirror)

利用 Swift 的反射机制动态生成字典:

extension Encodable {
    func toDictionary() -> [String: Any] {
        let mirror = Mirror(reflecting: self)
        var dict = [String: Any]()
        for child in mirror.children {
            if let key = child.label {
                dict[key] = child.value
            }
        }
        return dict
    }
}

let dict = person.toDictionary()
print(dict) // ["name": "Alice", "age": 30]

注意事项

  • Codable 方法适用于属性均为 Codable 类型的情况,且可能涉及性能开销。
  • 手动转换适合属性较少或需要定制化的场景。
  • 反射方式灵活性高,但可能丢失类型信息或遇到复杂类型的处理问题。

选择方法时需根据具体需求和结构体复杂度权衡。

你可能感兴趣的:(swift)