问题描述
例如:
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可以将类/结构数据转换成字典吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!