例如:
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();
字典将包含以下内容:
{"name": "Alex", "age": 30, height: 170}
在Swift中有可能吗?
我是否可以访问像字典这样的类,例如可能使用:
test.value(forKey: "name");
或类似的东西?
谢谢。
您只需将计算属性添加到您的属性中struct即可返回Dictionary带有您的值的。请注意,Swift本机字典类型没有任何称为的方法value(forKey:)。您需要将您强制转换Dictionary为NSDictionary:
struct
Dictionary
value(forKey:)
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 } }
您还可以Encodable按照@ColGraff发布的链接答案中的建议扩展协议,以使其对所有Encodable结构通用:
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