ios - 如何在 swift 3 中为多个值实现模型类?

标签 ios swift

这里我在 JSON 中有 value,其中对于多个键值对中的一些,它返回字符串,对于一些它返回数组,在 value 的第一个字典的自定义属性数组中 键值对存在的数据不同,在第二个字典中 value 键值对在这里不同那么如何为不同的键值实现内部数组的模型类?

struct MediaGallery {

    let id : Int
    let mediaType : String
    let label : Any
    let position : Int
    let disabled : Any
    let file : String

    init(dict : [String:Any]) {
        self.id = (dict["id"] as? Int)!
        self.mediaType = (dict["media_type"] as? String)!
        self.label =  dict["label"]!
        self.position = (dict["position"] as? Int)!
        self.disabled = dict["disabled"]!
        self.file = (dict["file"] as? String)!
    }
}
struct AttributeList {

    let label : String
    let value : String
    let code : String

    init(dict : [String:Any]){

        self.label = (dict["label"])! as! String
        self.value = (dict["value"])! as! String
        self.code = (dict["code"])! as! String
    }
}
struct DetailsListAttribute {

    let attributeCode : String
    let value : Any

    init?(dict : [String:Any]) {

        self.attributeCode = dict["attribute_code"] as! String
        print(self.attributeCode)
        if let values = dict["value"] as? String {
            self.value = values
        }
        else {
            if let arr = dict["value"] as? [[String:Any]]{
                var filterArr = [AttributeList]()
                for obj in arr {
                    filterArr.append(AttributeList(dict: obj))
                }
                self.value = filterArr
            } else {
                self.value = [AttributeList]()
            }
        }

    }
}

最佳答案

我建议使用这个很棒的 GIT 库来节省一些时间 ObjectMapper .它将帮助您对对象建模并将模型对象(类和结构)转换为 JSON,反之亦然。

关于ios - 如何在 swift 3 中为多个值实现模型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47197737/

相关文章:

ios - 使用 AVAudioEngine 进行电平测量

ios - 两台苹果电脑。一份 iPhone 开发者许可证。可能的?

ios - Xcode 允许你从 Assets.xcassets 中制作一个 "sprite Atlas",它实际上是一个图集吗?

string - UISearchBar textDidChange,searchtext 变量无法与 rangeOfString 一起使用?

ios - NSPersistentContainer 默认创建什么样的持久化存储?

ios - TableView 折叠/展开部分

ios - 如何在 iOS 中通过键盘显示 UIView

swift - 动画完成 Collection View Cell 而不是 Image

swift - 使用带绑定(bind)的 ForEach 循环会导致数组缩小时索引超出范围(SwiftUI)

ios - 我需要做什么才能让 UIImagePickerController 在横向模式下使用 swift?