Swift报错NSArray element failed to match the Swift Array Element type

使用字典转模型时报错
由于XYSpecial模型中有一个属性是另一个模型的数组,我在自定义构造函数中使用setValuesForKeys(dict)进行字典转模型,导致报错
NSArray element failed to match the Swift Array Element type

解决方法:由于未使用第三方字典转模型框架,我将字典中所有的value单独赋值给模型的属性就解决了, 或者使用KVC一个一个转换也可以setValue(<#T##value: Any?##Any?#>, forKey: <#T##String#>)

class XYSpecial: NSObject {

    // MARK:- 属性
    var scId : Int?
    var title : String?             // 专题活动标题
    var subTitle : String?          // 专题活动子标题
    var desc : String?              // 专题活动描述
    var smallPicUrl : String?
    var largePicUrl : String?
    var mainPicUrl : String?        // 专题详情页的头部图片
    var createTime : String?        // 创建时间
    var pubTime : String?           // 出版时间
    var weight : Int?
    var hitCount : Int?
    var hasDel : Int?
    var threadId : Int?
    var chosen : Int?
    var itemList : [XYArticleItem] = [XYArticleItem]()    // 专题活动的物品模型数组
    
    
    // MARK:- 自定义构造函数
    init(dict: [String: Any]) {
        super.init()
        
        if let list = dict["itemList"] as? [[String : Any]] {
            for obj in list {
                let articleItem = (XYArticleItem(dict: obj))
                
                itemList.append(articleItem)
            }
        }
        
        self.scId = dict["scId"] as! Int?
        self.title = dict["title"] as! String?
        self.subTitle = dict["subTitle"] as! String?
        self.desc = dict["desc"] as! String?
        self.smallPicUrl = dict["smallPicUrl"] as! String?
        self.largePicUrl = dict["largePicUrl"] as! String?
        self.mainPicUrl = dict["mainPicUrl"] as! String?
        self.createTime = dict["createTime"] as! String?
        self.pubTime = dict["pubTime"] as! String?
        self.weight = dict["weight"] as! Int?
        self.hitCount = dict["hitCount"] as! Int?
        self.hasDel = dict["hasDel"] as! Int?
        self.threadId = dict["threadId"] as! Int?
        self.chosen = dict["chosen"] as! Int?
    }
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容