首页 > 代码库 > 字典 -> model

字典 -> model

1.使用KVC

init(dict : [String : Any]) {
        super.init()
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forKey key: String) {
        super.setValue(value, forKey: key)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }

2.例子

1.先分别定义3个class,Person,Room,Friend
2.定义对应的属性,添加1中的代码
   注意: 定义属性,要么为可选类型,那么就设置初始值
3.最后在Person实现
class Person: NSObject {

    //1.要设置为可选类型,要不就设置初始值
    var fr : Friend?
    var rm : [Room]?
    
    var name : String?
    var age  : Int = 0
    //字典
    var friend : [String : Any]? {
        didSet {
            fr = Friend(dict : friend!)
        }
    }
    //model数组
    var room : [[String : Any]]? {
        didSet {
            var array = [Room]()
            for value in room! {
                let k = Room(dict: value)
                array.append(k)
            }
            rm = array
        }
    }
    var image : [String]?
    
    
    init(dict : [String : Any]) {
        super.init()
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forKey key: String) {
        super.setValue(value, forKey: key)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }

    
}


let dict = ["name" : "kk" , "age" : 10 , "friend" : ["name" : "yy" , "girl" : "lyh"]  , "room" : [["size" : 8 , "bag" : "hello"] , ["size" : 6 , "bag" : "ko"]] , "image" : ["a" , "b" , "c"]] as [String : Any]
        
let p = Person(dict: dict)

//对于room,friend属性不直接使用,而使用rm, fr的model来代替

 

字典 -> model