Swift 可以将类/结构数据转换为字典吗? [英] Can Swift convert a class / struct data into dictionary?

查看:45
本文介绍了Swift 可以将类/结构数据转换为字典吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

class Test {
    var name: String;
    var age: Int;
    var height: Double;
    func convertToDict() -> [String: AnyObject] { ..... }
}

let test = Test();
test.name = "Alex";
test.age = 30;
test.height = 170;

let dict = test.convertToDict();

dict 会有内容:

{"name": "Alex", "age": 30, height: 170}

这在 Swift 中可行吗?

Is this possible in Swift?

我可以访问像字典这样的类吗,例如可能使用:

And can I access a class like a dictionary, for example probably using:

test.value(forKey: "name");

或者类似的东西?

谢谢.

推荐答案

您只需将计算属性添加到您的 struct 即可返回带有您的值的 Dictionary.请注意,Swift 本机字典类型没有任何称为 value(forKey:) 的方法.您需要将 Dictionary 转换为 NSDictionary:

You can just add a computed property to your struct to return a Dictionary with your values. Note that Swift native dictionary type doesn't have any method called value(forKey:). You would need to cast your Dictionary to NSDictionary:

struct Test {
    let name: String
    let age: Int
    let height: Double
    var dictionary: [String: Any] {
        return ["name": name,
                "age": age,
                "height": height]
    }
    var nsDictionary: NSDictionary {
        return dictionary as NSDictionary
    }
}

<小时>

您还可以按照@ColGraff 发布的链接答案中的建议扩展 Encodable 协议,使其适用于所有 Encodable 结构:


You can also extend Encodable protocol as suggested at the linked answer posted by @ColGraff to make it universal to all Encodable structs:

struct JSON {
    static let encoder = JSONEncoder()
}
extension Encodable {
    subscript(key: String) -> Any? {
        return dictionary[key]
    }
    var dictionary: [String: Any] {
        return (try? JSONSerialization.jsonObject(with: JSON.encoder.encode(self))) as? [String: Any] ?? [:]
    }
}

<小时>

struct Test: Codable {
    let name: String
    let age: Int
    let height: Double
}

let test = Test(name: "Alex", age: 30, height: 170)
test["name"]    // Alex
test["age"]     // 30
test["height"]  // 170

这篇关于Swift 可以将类/结构数据转换为字典吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆