ios - 如何从 Swift 中的 JSON 模型类中获取键值?
问题描述
我在 Swift 中为我的应用程序获得了一些 API 响应。因此,我将这些数据保存到 CoreData 中以用于实体并获取。
获取后,我正在制作用于获取数据的模型类,并且正在传递它。因此,我必须获取该模型类数据,并需要在表格视图单元格中将其显示为键值。
但是,我无法获取模型类,但我能够将数据从数据库数据传递到模型类。
型号类:
struct AccountInfoModel {
var name: String?
var birthdate: String?
var age: String?
init(dict: [String:AnyObject]) {
self.name = dict[AccountinfoKeyConstant.Profile_name] as? String
self.birthdate = dict[AccountinfoKeyConstant.Profile_Birthdate] as? String
self.age = dict[AccountinfoKeyConstant.Profile_Age] as? String
}
}
func fetchProfileData() {
do {
let profileData = try? Profile.fetchProfileInfo()
if let profileInfo = profileData {
// print("profileInfo \(profileInfo)")
let profile = AccountInfoModel.init(dict: profileInfo as [String : AnyObject])
print("profile \(profile)")
}
如何从模型类中获取数据作为键值显示在表格视图中?实际上,我与 Swift 的合作并不多。有什么建议么?
解决方案
我自己解决了这个问题。我刚刚完成模型类初始化,然后将数据传递给模型类。
之后,我通过将模型类数据传递给某个方法来将键值构造到某个字典中。
var accountInfoModel = [AccountInfoModel]()
func fetchProfileData() {
do {
let profileData = try? Profile.fetchProfileInfo()
if let profileInfo = profileData {
accountInfoModel = [AccountInfoDBModel.init(dict: profileInfo as [String : AnyObject])]
let data = self.accountInfoModel[0]
print("age is \(data.age)")
}
现在,它工作正常,我希望这会对某人有所帮助。
推荐阅读
- python - Pandas:如何检查在另一列特定值之后是否存在一系列正值
- sql-server - 在 SQL 变量中存储多个变量并将其用于删除表中的条目
- bash - 在 file.txt 中回显命令结果
- python - 使用 HLS 流式传输实时图像
- vb.net - datagridView 过滤和排序 vb.net
- mysql - 无法添加或更新子行:数据存在时外键约束失败
- linux - 为我的嵌入式设备定义一个干净且有效的 asound.conf
- android - 与屏幕一起移动顶部导航栏
- regex - 期望:^ 在描述不同 Cisco 设备的命令提示符的正则表达式中不起作用
- javascript - 根据整个路径轨迹的百分比在路径轨迹上移动 SVG 组