将Swift Object转换为Dictionary [复制]

pepwfjgg  于 2023-04-28  发布在  Swift
关注(0)|答案(4)|浏览(164)

此问题已在此处有答案

How can I use Swift’s Codable to encode into a dictionary?(16个答案)
2天前关闭。
我有以下类:

class Person {
    let name: String
    let surname: String

    init(name: String, surname: String) {
        self.name = name
        self.surname = surname
    }
}

如何将Person(name: "Mike", surname: "Wasowski")转换为字典?

brjng4g3

brjng4g31#

class Person {
        let name: String
        let surname: String

        init(name: String, surname: String) {
            self.name = name
            self.surname = surname
        }
        func convertIntoDict() -> Dictionary<String, String> {
            var dict = Dictionary<String, String>()
            dict["name"] = self.name
            dict["surname"] = self.surname
            return dict
        }
    }

let dict = Person(name: "Mike", surname: "Wasowski").convertIntoDict()

//// ["name": "Mike", "surname": "Wasowski"]
yc0p9oo0

yc0p9oo02#

在Person类中添加新方法toDictionary,并执行以下代码:

class Person {
    let name: String
    let surname: String

    init(name: String, surname: String) {
        self.name = name
        self.surname = surname
    }

    func toDictionary() -> [String:Any]
    {
        var dictionary = [String:Any]()
        dictionary["name"] = name
        dictionary["surname"] = surname
        return dictionary
    }
}

示例:

let person = Person(name: "Girish", surname: "Chovatiya")
let dic = person.toDictionary()
print(dic)
syqv5f0l

syqv5f0l3#

方式一:

class Person {
    let name: String
    let surname: String

    var dict: [String:String]?

    init(name: String, surname: String) {
        self.name = name
        self.surname = surname 
        self.dict = ["name":name, "surname":surname]
    }
}

第二路

class Person {
    let name: String
    let surname: String?

    init(name: String, surname: String) {
        self.name = name
        self.surname = surname 
    }

    func getDict() -> [String:String] {
       return ["name":name, "surname":surname]
    } 

}
dwbf0jvd

dwbf0jvd4#

下面是一个不使用键名称的优雅方法:

func toDictionary() -> [String: Any] {
        var dict: [String: Any] = [:]
        let mirror = Mirror(reflecting: self)
        
        for case let (label?, value) in mirror.children {
            dict[label] = value
        }
        
        return dict
    }

相关问题