[swift]-类的构造函数

前端之家收集整理的这篇文章主要介绍了[swift]-类的构造函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1:两种基本的构造函数

01-自定义构造函数:传入基本参数

  1. > 01-init(name : String,age : Int) {
  2. self.name = name
  3. self.age = age
  4. }

02-自定义构造函数:传入一个字典

  1. init(dict : [String : AnyObject]) {
  2. super.init()
  3. // kvc 调用对象的KVC方法字典转模型
  4. //self.setValuesForKeysWithDictionary(dict)
  5. setValuesForKeysWithDictionary(dict)
  6. }

// 注意:凡是使用kvc了,都要重写:override func setValue(value: AnyObject?,forUndefinedKey key: String) {} ;因为字典里某些字段不是类的属性就可以不会报错了

  1. override func setValue(value: AnyObject?,forUndefinedKey key: String) {}

知识点1:

  1. // as? 最终转成的类型是一个可选类型
  2. // as! 最终转成的类型是一个确定的类型,非可选类型

知识点2:

在类里调用对象的方法如kvc方法:self可以省略,//self.setValuesForKeysWithDictionary(dict) 简写成:setValuesForKeysWithDictionary(dict)

知识点3:

一般情况下,super.init(),我们不调用,系统会自动调用,系统调用是在该方法最后调用,但是当我们调用系统的kvc方法的时候,我们一定要确保该对象已经创建了,所以我们需要提前手动调用super.init()这个方法,如:

  1. init(dict : [String : AnyObject]) {
  2. // 提前调用super.init(),确保该对象已经创建了,不然怎么调用对象的一个kvc的方法
  3. // 一般系统会默认调用super.init(),都是在该方法的最后的地方调用,这时候已经晚了,我们需要在调用kvc方法前就需要调用
  4. super.init()
  5. // kvc 调用对象的KVC方法字典转模型
  6. //self.setValuesForKeysWithDictionary(dict)
  7. setValuesForKeysWithDictionary(dict)
  8. }

2:代码演示:

  1. import UIKit
  2.  
  3. class Person: NSObject {
  4. var name : String?
  5. var age : Int = 0
  6. // 在构造函数中,如果没有明确super.init(),name系统会自动帮我们调用super.init()
  7. override init() {
  8. //super.init()
  9. print("1111111")
  10. }
  11. // 自定义构造函数:传入基本参数
  12. init(name : String,age : Int) {
  13. print("22222")
  14. self.name = name
  15. self.age = age
  16. }
  17. // 自定义构造函数:传入一个字典
  18. // init(dict : [String : AnyObject]) {
  19. // let tempName = dict["name"]
  20. // //tempName是一个AnyObject?类型,转成String?
  21. // // as? 最终转成的类型是一个可选类型
  22. // // as! 最终转成的类型是一个确定的类型,非可选类型
  23. // name = tempName as? String
  24. //
  25. //
  26. //// let tempAge = dict["age"]
  27. //// //age = tempAge as! Int
  28. //// let tempAge1 = tempAge as? Int
  29. //// if tempAge1 != nil {
  30. //// age = tempAge1!
  31. //// }
  32. //// print(age)
  33. //
  34. // if let tempAge = dict["age"] as? Int {
  35. // age = tempAge
  36. // }
  37. // }
  38. init(dict : [String : AnyObject]) {
  39. // 提前调用super.init(),确保该对象已经创建了,不然怎么调用对象的一个kvc的方法
  40. // 一般系统会默认调用super.init(),都是在该方法的最后的地方调用,这时候已经晚了,我们需要在调用kvc方法前就需要调用
  41. super.init()
  42. // kvc 调用对象的KVC方法字典转模型
  43. //self.setValuesForKeysWithDictionary(dict)
  44. setValuesForKeysWithDictionary(dict)
  45. }
  46. override func setValue(value: AnyObject?,forUndefinedKey key: String) {}
  47. }
  48.  
  49.  
  50. //let p = Person()
  51. //let p1 = Person(name: "sky",age: 19)
  52. //if let name = p1.name {
  53. // print(name)
  54. //}
  55. //print(p1.age)
  56.  
  57.  
  58. let p2 = Person(dict: ["name" : "mike","age" : 18,"height" : 1.88])
  59. print(p2.age)
  60. if let name = p2.name {
  61. print(name)
  62. }


意见反馈邮件:1415429879@qq.com 欢迎你们的阅读和赞赏、谢谢!

猜你在找的Swift相关文章