首页 > 解决方案 > 如何从 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 的合作并不多。有什么建议么?

标签: iosswiftstruct

解决方案


我自己解决了这个问题。我刚刚完成模型类初始化,然后将数据传递给模型类。

之后,我通过将模型类数据传递给某个方法来将键值构造到某个字典中。

    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)")

}

现在,它工作正常,我希望这会对某人有所帮助。


推荐阅读