gpt4 book ai didi

swift - Swift 可以将类/结构数据转换为字典吗?

转载 作者:IT王子 更新时间:2023-10-29 05:28:24 24 4
gpt4 key购买 nike

例如:

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 中可能吗?

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

test.value(forKey: "name");

或者类似的东西?

最佳答案

您只需将计算属性添加到您的 struct 以返回包含您的值的 Dictionary。请注意,Swift 原生字典类型没有任何名为 value(forKey:) 的方法。您需要将 Dictionary 转换为 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 协议(protocol),使其对所有Encodable 结构通用:

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 - Swift 可以将类/结构数据转换为字典吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46597624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com