例如:
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}
这在斯威夫特中可能吗?
我可以访问像字典这样的类吗,例如可能使用:
test.value(forKey: "name");
或类似的东西?
您只需将计算属性添加到您的struct
返回一个Dictionary
与你的价值观。请注意,Swift 本机字典类型没有任何调用的方法value(forKey:)
。你需要投射你的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
}
}
您还可以延长Encodable
@ColGraff 发布的链接答案中建议的协议,使其对所有人通用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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)