当前位置: 代码迷 >> 综合 >> swift 3.0 类的构造函数
  详细解决方案

swift 3.0 类的构造函数

热度:60   发布时间:2023-12-15 01:24:56.0
/*//类的构造函数使用KVC条件1> 必须继承自NSObject2> 必须在构造函数中,先调用super.init(03> 调用setValueForKeys4> 如果字典中某一个key没有对应的属性,则需要重写setValueForKeys方法*/class LJPerson : NSObject{var name : String = ""var age : Int = 0var height : Double = 0init(name:String, age:Int) {self.name = nameself.age = age}//重写init方法init(dict : [String : Any]) {/*一般写法,假如此处有多个变量的话,要写好长好长的if let name = dict["name"] as? String {self.name = name}if let age = dict["age"] as? Int{self.age = age}if let height = dict["height"] as? Double{self.height = height}*/super.init()setValuesForKeys(dict)}//倘若不重写init方法的话,就不会出来init()override init() {}//重写这个方法,没有定义的key在里面也不会引起奔溃,如下面的key="phonum"override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}let pw = LJPerson()
let pfg = LJPerson(name: "sww", age: 18)
let ps = LJPerson(dict: ["name":"swgt","age":18,"height":1.09,"phonum":"139"])print(ps.name,ps.age)