Swift 5 从Model, Struct或Class转Dictionary

Posted 架构师易筋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift 5 从Model, Struct或Class转Dictionary相关的知识,希望对你有一定的参考价值。

将Struct(遵守Codable协议)用JSONEncoder的encode转成Data,然后再用JSONSerialization反序列化成Dictionary对象。

/// 直接将Struct或Class转成Dictionary
protocol Convertable: Codable {

}

extension Convertable {

    /// 直接将Struct或Class转成Dictionary
    func convertToDict() -> Dictionary<String, Any>? {

        var dict: Dictionary<String, Any>? = nil

        do {
            print("init student")
            let encoder = JSONEncoder()

            let data = try encoder.encode(self)
            print("struct convert to data")

            dict = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? Dictionary<String, Any>

        } catch {
            print(error)
        }

        return dict
    }
}

struct Student: Convertable {

    var name: String
    var age: Int
    var classRoom: String

    init(_ name: String, age: Int, classRoom: String) {
        self.name = name
        self.age = age
        self.classRoom = classRoom
    }
}

let student = Student("zgpeace", age: 28, classRoom: "06242班")

print(student.convertToDict() ?? "nil")

参考

https://a1049145827.github.io/2018/03/02/Swift-%E4%BB%8E%E9%9B%B6%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AAStruct%E6%88%96Class%E8%BD%ACDictionary%E7%9A%84%E9%9C%80%E6%B1%82/

以上是关于Swift 5 从Model, Struct或Class转Dictionary的主要内容,如果未能解决你的问题,请参考以下文章

Swift Struct 结构体

我如何从 struct 获取纬度和经度并在 mapbox Swift 上显示它们

swift protocol(协议) associatedtype关联类型

Swift Struct 的引用计数

Swift class和struct异同点

Swift:模型结构,使用可选项与空值的初始化