Swift Construction and destruction

Source: Internet
Author: User

Objective
    • As with OC, there are construction and destruction processes in Swift. The difference is that the constructor and destructor methods in OC are only ordinary methods, and the constructors and destructors in Swift are a special kind of structure.
1. Constructors
  • In Swift, classes or structs must be initialized to ensure that all of the properties contained in them are initialized, that the constructor is used to initialize the properties in the class or struct, and that the formal constructor and method are similar, but it is not a method.

    • The declaration constructor does not require a func keyword.
    • Similar to OC, use the init table justification in Swift.
    • There can be more than one constructor in a class or struct, and all constructors are called init , and the system uses the overloaded attributes to determine which constructor to use.
    • You can use the same name as the property on the parameter name, and if the name of the parameter in the constructor is the same as the name of the property, use the self keyword to mark the attribute.
    • In the class, Swift provides three constructors to initialize: a constructor, a convenience constructor, and a failed constructor are specified.

      // 指定构造器init(参数名1: 参数类型, 参数名2: 参数类型, ...) {    statements}
      // 便利构造器convenience init(参数名1: 参数类型, 参数名2: 参数类型, ...) {    statements}
      // 可失败构造器init?(参数名1: 参数类型, 参数名2: 参数类型, ...) {    statements}
  • In some cases, a constructor is automatically generated by the system.

    • If you are in a class, when all the properties in a class have an initial value, and the constructor is not defined in the class, you get a constructor with no arguments init() .
    • If you are in a struct, when all the properties in a class have an initial value, and the constructor is not defined in the struct, you get a constructor that defaults to all the properties as arguments.
  • Considerations when using constructors.

    • When any constructor is complete, you must ensure that all properties are initialized, even if the value of the optional property is nil , it has a value.
    • Methods and properties in the calling class must be completed before initialization is complete.
  • In Swift, an inherited initialization method is used.

    • When the constructor of a parent class and a subclass interacts, it is interacted with by the respective specified constructor.
    • The convenience constructor only cares about the other constructors in this class, not the constructors of the parent class or subclass.
    • If you precede the constructor with a required keyword, the subclass of the class must implement its constructor.
1.1 Specifying constructors
  • Specifies that the constructor contains the system auto-generated constructor and all constructors other than the convenience constructor and the failed constructor, which is the default initialization method.

    • Specifies that the constructor must init call the specified constructor of the parent class in, and cannot call its own other constructors.

      init(参数名1: 参数类型, 参数名2: 参数类型, ...) {    statements}
  • If no specified constructors are implemented in the class, all specified constructors in the parent class are inherited.

     //parent class Transport {var scope = "" init () {}/ /No parameter specifies the constructor init (str:string) {////has a parameter for the specified constructor self.scope = str}}  
    //Subclass class Car:transport {//does not implement any of the specified constructors in the class}
     //use let MyCar = Car ()//Use the parameterless constructor in the parent class let Mynewcar = Car (str: "Ludi")//constructor with a parameter in the parent class  
  • Once you have created your own specified constructor in a subclass, you will no longer be able to use the constructor in the parent class, and a specified constructor in the parent class needs to be called in the specified constructor declaration in the child class.

    // 父类class Transport {    var scope = ""    init() {}                                       // 无参数指定构造器    init(str: String) {                             // 有一个参数的指定构造器        self.scope = str    }}
    // 子类class Car: Transport {    var wheel = "pulisitong"    init(scope: String, wheel: String) {            // 创建自己的指定构造器        super.init()                                // 指定构造器必须调用父类的指定构造器        self.scope = scope        self.wheel = wheel    }}
    // 使用let myCar = Car(scope: "ludi", wheel: "miqilin")    // 此时不能使用父类中无参或者有一个参数的构造器
1.2 Convenience Builder
  • The constructor for
  • Calls to other constructors is called a convenience constructor. The

    • convenience Builder must call an additional constructor. The
    • convenience constructor must call the specified constructor directly or indirectly to access other values, and it can invoke the specified constructor indirectly by invoking other convenience constructors.
    • If a convenience constructor wants to invoke the specified constructor, it must and can only invoke the specified constructor in this class, not the constructor of any parent class.

        convenience init (parameter name 1: argument type, Parameter name 2: Parameter type, ...)
       {statements}  
  • If all the specified constructors in the parent class are overridden in a subclass, all the convenience constructors in the parent class are inherited.

    // 父类class Transport {    var scope = ""    init() {}                                       // 无参数指定构造器    init(str: String) {                             // 有一个参数的指定构造器        self.scope = str    }    convenience init(scope: String) {               // 便利构造器        self.init(str: scope)                       // 调用自身类的指定构造器    }}
    // 子类class Car: Transport {    override init() {                               // 重写父类指定构造器        super.init()                                // 指定构造器必须调用父类的指定构造器    }    override init(str: String) {                    // 重写父类指定构造器        super.init()                                // 指定构造器必须调用父类的指定构造器        self.scope = "Car" + str    }}
    // 使用let myCar = Car(scope: "ludi")                      // 调用父类的便利构在器
1.3 Can fail the constructor
    • There are some initialization methods that allow failure and return nil .

      • Can be followed by one in the definition of the failed constructor init ? .

        init?(参数名1: 参数类型, 参数名2: 参数类型, ...) {    statements}
    • This type of failure constructor is usually recommended if-let for use or guard-let-else structure, and if the initialization succeeds, the operation is performed, otherwise the operation is done.

      • if-letStructure

        if let image = UIImage(named: "test") {    // 执行与 image 有关的代码} else {    // 执行与 image 无关的代码}
      • guard-let-elseStructure

        guard let image = UIImage(named: "test") else {    // 执行与 image 无关的代码}// 执行与 image 有关的代码
1.4 Anonymous Constructors
    • Sometimes subclasses of some kind of object we create only once, there is no need to write a constructor specifically.

      • An anonymous constructor is created using closures, which need to be added () to tell Swift to execute the closure immediately, otherwise the closure itself is assigned as a value to the property.

        let button: UIButton = {    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))    button.backgroundColor = UIColor.white    return button}()
      • Use a different object method to create an anonymous constructor.

        let someArray = ["1", "2", "3"]let someString = someArray.joined(separator: ", ")print(someString)                 // 1, 2, 3
2, the destructor
    • Corresponding to the constructor, Swift also provides a destructor for releasing the object.

      • Destructors apply only to classes.
      • Only one destructor can be defined in a class.
      • The destructor is defined in the same way as the constructor, using the keyword deinit , and the destructor has no parameters.

        deinit() {    // 执行析构过程}
    • When the object is set to nil , the destructor is called automatically.

      deinit {    self.conn.close()    self.conn = nil}
    • Because automatic reference counting (ARC) is introduced in Swift, there is no need for the reader to manage memory manually, but a destructor is required when using some of its own resources.

      • For example, I want to create a database access class, open the link at initialization, if the program exits, the connection is not released, the resources will be wasted.
    • Value types do not have a destructor because value types do not appear "shared," and each value type has only one owner.

      • For example, a value type is recycled when its owner is reclaimed by the system, and we do not need to care about the life cycle of the value type.

Swift Construction and destruction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.