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

查看:101
本文介绍了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将包含以下内容:

dict will have content:

{"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天全站免登陆