美文网首页swift
iOS Swift5 构造函数分析(一):关键字 designa

iOS Swift5 构造函数分析(一):关键字 designa

作者: 青叶小小 | 来源:发表于2021-02-25 01:40 被阅读0次

    在 swift 中,构造函数的要求比较严格,而我们聊的这三个关键字都于构造函数相关!

    二、关键字说明

    1. designated(中文含义:指定的) :它指的是我们定义的公开的构造函数;公开的构造函数至少有一个,也可以有多个;
    2. convenience(中文含义:便利的):我们可以用该关键字来扩展(即新增)构造函数,因此是修饰构造函数的,但需要注意几点:
      • 必需在同一个类中使用;
      • 必需调用一个 designated 构造函数,调用时使用的是 self.init,而不是 super.init;
      • 子类无法继承重载被 convenience 修饰的构造方法;
    3. required(中文含义:必要的) :含义很直白,即子类必需要实现父类指定的构造函数;

    关键字 designated 和 convenience 修饰构造函数的关系: initializerDelegation.png

    三、Demo演示

    3.1、定义基类 People

    class People {
        var name: String
        var age : Int
        var sexy: Int
        
        /// designated
        /// 指定一个构造函数
        init(_ name: String, age: Int, sexy: Int) {
            self.name = name
            self.age = age
            self.sexy = sexy
        }
    
        convenience init(_ name: String, age: Int) {
            self.init(name, age: age, sexy: 0)
        }
        
        required init(_ name: String) {
            self.name = name
            self.age = 0
            self.sexy = 0
        }
    }
    

    3.2、定义子类 Student

    当我们重载Peopleinit(_ name: String, age: Int, sexy: Int)方法时,xcode会马上提示如下错误:

    cons-required.png

    然后,我们点击Fix后,xcode 自动添加如下代码:

    intros.png

    添加点说明注释,代码如下:

    class Student: People {
        // 父类的 designated 构造方法,子类可以进行重载
        override init(_ name: String, age: Int, sexy: Int) {
            super.init(name, age: age, sexy: sexy)
        }
        
        // 父类的 convenience 构造方法,子类无法继承
        
        // 父类的 required 构造方法,子类必须实现
        required init(_ name: String) {
            fatalError("init(_:) has not been implemented")
        }
    }
    

    相关文章

      网友评论

        本文标题:iOS Swift5 构造函数分析(一):关键字 designa

        本文链接:https://www.haomeiwen.com/subject/iwxyfltx.html