iOS Swift5 语法

Swift语法 Swift5 【12 - 初始化器init】

2020-05-13  本文已影响0人  Liwx

iOS Swift 语法 底层原理内存管理分析 专题:【iOS Swift5语法】

00 - 汇编
01 - 基础语法
02 - 流程控制
03 - 函数
04 - 枚举
05 - 可选项
06 - 结构体和类
07 - 闭包
08 - 属性
09 - 方法
10 - 下标
11 - 继承
12 - 初始化器init
13 - 可选项


目录


01-初始化器



// 指定初始化器
init(parameters) {
    statements
}

// 便捷初始化器
convenience init(parameters) {
    statements
}

class Size {
    var width: Int = 0
    var height: Int = 0
//    init() {    // 编译器生成这种无参初始化器
//
//    }
}
var size = Size()

class Size {
    var width: Int = 0
    var height: Int = 0
    init(width: Int, height: Int) {    // 编译器生成这种无参初始化器
        self.width = width
        self.height = height
    }
}
//var size = Size()   // error: missing arguments for parameters 'width', 'height' in call
var size = Size(width: 10, height: 20)

class Size {
    var width: Int = 0
    var height: Int = 0
    
    init() {
        
    }
    
    convenience init(width: Int, height: Int) {
        // 便捷最终必须调用一个指定初始化器
        self.init()         // 如果没调用self.init(), error: 'self' used before 'self.init' call or assignment to 'self'
        self.width = width
        self.height = height
    }
}
var s1 = Size()
var s2 = Size(width: 10, height: 10)

class Size {
    var width: Int = 0
    var height: Int = 0
    
    // 指定初始化器(主要初始化器)
    init(width: Int, height: Int) {
        self.width = width
        self.height = height
    }
    
    convenience init(width: Int) {
        self.init(width: width, height: 0) // 如果没调用指定初始化器 error: 'self' used before 'self.init' call or assignment to 'self'
        self.width = width
    }
    
    convenience init(height: Int) {
        self.init(width: 0, height: height)
        self.height = height
    }
    
    convenience init() {
        self.init(width: 0, height: 0)
    }
}
var s1 = Size()
var s2 = Size(width: 10, height: 10)
var s3 = Size(width: 10)
var s4 = Size(height: 20)

class Person {
    var age: Int = 0
    init(age: Int) {
        self.age = age
    }
    
    convenience init() {
        self.init(age: 0)
    }
}

class Student : Person {    // 类继承冒号左右最好空一格
    var score: Int
    init(age: Int, score: Int) {
        
        // 指定初始化器必须从它的直系父类调用指定初始化器
        self.score = score // 注意: 不能写到super.init(age: age)之后, 否则报错 error: property 'self.score' not initialized at super.init call
        super.init(age: age)
        
        // error: 'super.init' isn't called on all paths before returning from initializer
//        self.age = age
//        self.score = score
    }
    
    
    init() {
        
        // 子类的指定初始化器不能直接调用本身的指定初始化器
//        self.init(age: 0, score: 0) // error: designated initializer for 'Student' cannot delegate (with 'self.init'); did you mean this to be a convenience initializer?
        
        self.score = 0
        super.init(age: 0)
    }
}

//var stu1 = Student(age: 10) // 如果子类自定义初始化器,不会自动继承直系父类的初始化器,因为这样会导致父类的存储属性为能初始化 error: missing argument for parameter 'score' in call
var stu2 = Student(age: 10, score: 20)

02-初始化器的相互调用



QQ20200510-191425@2x.png

03-两段式初始化

class Person {
    var age: Int = 0
    init(age: Int) {
        self.age = age
        // 此次可以个性化定制
    }
    
    convenience init() {
        self.init(age: 0)
        // 此次可以个性化定制
    }
}

class Student : Person {
    var score: Int
    init(age: Int, score: Int) {
        
        // 存储属性未完成初始化指针,不能用self
//        print(self) // error: 'self' used before 'super.init' call
//        self.age = 10   // error: 'self' used in property access 'age' before 'super.init' call
//        self.test() // error: 'self' used in method call 'test' before 'super.init' call
//        var fn = {  // error'self' captured by a closure before all members were initialized
//            self.age = 20
//        }
//        fn()
        
        self.score = score
        super.init(age: age)
        // 此次可以个性化定制
    }
    
    init() {
        self.score = 0
        super.init(age: 0)
        // 此次可以个性化定制
        self.test()
    }
    
    func test() {
        print("age: \(age), score: \(score)")
    }
}

04-安全检查


QQ20200510-201532@2x.png
class Person {
    var age: Int = 0
    init(age: Int) {
        self.age = age
        // 此次可以个性化定制
    }
    
    convenience init() {
        self.init(age: 0)
        // 此次可以个性化定制
    }
}

class Student : Person {
    var score: Int
    init(age: Int, score: Int) {
        self.score = score
        super.init(age: age)
    }
    
    init() {
        self.score = 0
//        self.age = 20   // 初始化器在`第1阶段初始化完成之前`,`不能调用任何实例方法`、`不能读取任何实例属性的值`,也`不能引用self`
        super.init(age: 0)
        // `指定初始化器`必须`先调用父类指定初始化器`,然后才能为`继承的属性设置新值`
        self.age = 10   // age是从父类继承的属性
        self.test()
    }
    
    convenience init(score: Int) {
        self.init(age: 0, score: score)
        // `便捷初始化器`必须先调用`同类中的其它初始化器`,然后再为`任意属性设置新值`
        self.age = 10
        self.score = 20
    }
    
    func test() {
        print("test")
    }
}

05-重写

class Person {
    var age: Int = 0
    init(age: Int) {
        self.age = age
    }
    
    // 因为父类的便捷初始化器永远不会通过子类直接调用,因此,严格来说,子类无法重写父类的便捷初始化器
    convenience init() {
        self.init(age: 0)
    }
}

class Student : Person {
    var score: Int
    
    init(age: Int, score: Int) {
        self.score = score
        super.init(age: age)
    }
    
    // 当`重写父类的指定初始化器`时,必须加上`override` (`即使子类的实现是便捷初始化器`)
    // 重写为指定初始化器
//    override init(age: Int) {
//        self.score = 0
//        super.init(age: age)
//    }
    
    // 重写为便捷初始化器
//    override convenience init(age: Int) {
//        self.init(age: age, score: 0)
//
//    }
    
    // 如果`子类`写了一个`匹配父类便捷初始化器`的初始化器,`不用加上override`
    // 子类写了匹配父类的便捷初始化器的指定初始化器(不算重写, 重写表示调用super.init())
//    init() {
//        self.score = 0
//        super.init(age: 0)
//    }
    
    // 子类写了匹配父类的便捷初始化器的便捷初始化器(不算重写, 重写表示调用super.init())
    convenience init() {
        self.init(age: 0, score: 0)
    }
    
}

06-自动继承


class Person {
    var age: Int = 0
    var name: String
    
    init(age: Int, name: String) {
        self.age = age
        self.name = name
    }
    
    init(age: Int) {
        self.age = age
        self.name = ""
    }
    
    init() {
        self.age = 0
        self.name = ""
    }
}

class Student : Person {
    
}

var stu1 = Student(age: 10)
var stu2 = Student(age: 10, name: "Liwx")

class Person {
    var age: Int = 0
    var name: String
    
    init(age: Int, name: String) {
        self.age = age
        self.name = name
    }
    
    init(age: Int) {
        self.age = age
        self.name = ""
    }
    
    init() {
        self.age = 0
        self.name = ""
    }
}

class Student : Person {
    override init() {
        super.init()
    }
}
var stu1 = Student()
//var stu2 = Student(age: 10) // 如果子类重写了初始化器,不会在自动继承父类的初始化器 error: argument passed to call that takes no arguments

class Person {
    var age: Int = 0
    var name: String
    
    init(age: Int, name: String) {
        self.age = age
        self.name = name
    }
    
    init(age: Int) {
        self.age = age
        self.name = ""
    }
    
    init() {
        self.age = 0
        self.name = ""
    }
}

class Student : Person {
    
    var no: Int = 0 // 参数必须初始化值,才能保证父类继承下来的初始化器能保证所有存储属性都设置了初始值
    convenience init(no: Int) {
        
//        self.no = no    // no存储属性未完成初始化, 不能调用self error: 'self' used before 'self.init' call or assignment to 'self'
        self.init(age: 0, name: "")
        // 所有存储已经初始化完成,可以个性化定制参数
        self.no = no
    }
}

var stu1 = Student()
var stu2 = Student(age: 10)
var stu3 = Student(age: 10, name: "Liwx")
var stu4 = Student(no: 20)

class Person {
    var age: Int = 0
    var name: String
    
    init(age: Int, name: String) {
        self.age = age
        self.name = name
    }
    
    init() {
        self.age = 0
        self.name = ""
    }
    
    convenience init(age: Int) {
        self.init(age: age, name: "")
    }
    
    convenience init(name: String) {
        self.init(age: 0, name: name)
    }
}

class Student : Person {
    
    // 2.如果子类提供了父类所有指定初始化器的实现(要么通过方式1继承,要么重写)
    // `子类自动继承所有`的`父类便捷初始化器`
    
    // 子类重写父类所有指定初始化器
    override init(age: Int, name: String) {
        super.init(age: age, name: name)
    }
    
    override init() {
        super.init()
    }
}

var stu1 = Student(age: 10, name: "Liwx")   // 子类提供了父类所有指定初始化器的实现,`子类自动继承所有`的`父类便捷初始化器`
var stu2 = Student()
var stu3 = Student(age: 10)
var stu4 = Student(name: "Liwx")

class Person {
    var age: Int = 0
    var name: String
    
    init(age: Int, name: String) {
        self.age = age
        self.name = name
    }
    
    init() {
        self.age = 0
        self.name = ""
    }
    
    convenience init(age: Int) {
        self.init(age: age, name: "")
    }
    
    convenience init(name: String) {
        self.init(age: 0, name: name)
    }
}

class Student : Person {
    convenience init(age: Int, name: String, no: Int) {
        self.init(age: age, name: name)
    }
}

class Person {
    var age: Int = 0
    var name: String
    
    init(age: Int, name: String) {
        self.age = age
        self.name = name
    }
    
    init() {
        self.age = 0
        self.name = ""
    }
    
    convenience init(age: Int) {
        self.init(age: age, name: "")
    }
    
    convenience init(name: String) {
        self.init(age: 0, name: name)
    }
}

class Student : Person {
    
    init(age: Int, name: String, no: Int) {
        super.init(age: age, name: name)
    }
    
    // 子类以便捷初始化器的形式重写父类的所有指定初始化器, 会自动继承父类的所有便捷初始化器
    convenience override init(age: Int, name: String) {
        self.init(age: age, name: name)
    }
    
    convenience override init() {
        self.init(age: 0, name: "")
    }
}

var stu1 = Student()
var stu2 = Student(age: 10)
var stu3 = Student(age: 10, name: "Liwx")
var stu4 = Student(age: 10, name: "Liwx", no: 20)
var stu5 = Student(name: "Liwx")

07-required


class Person {
    required init() { }
    init(age: Int) { }
}

class Student : Person {
    
}

var stu1 = Student()
var stu2 = Student(age: 10)

class Person {
    required init() { }
    init(age: Int) { }
}

class Student : Person {
    init(no: Int) {
        super.init()
    }
    required init() {
        super.init()
    }
}

var stu1 = Student()
var stu2 = Student(no: 20)
//var stu3 = Student(age: 10) // 子类重写了父类指定初始化器init()方法,没有重写父类的指定初始化器init(age:), 所以该初始化器不能使用  error: incorrect argument label in call (have 'age:', expected 'no:')

class Person {
    required convenience init() {
        self.init(age: 0)
    }
    init(age: Int) { }
}

class Student : Person {
    
    init(no: Int) {
        super.init(age: 0)
    }
    
    override init(age: Int) {
        super.init(age: age)
    }
    
    required convenience init() {
        self.init(age: 0)
    }
}

08-属性观察器

class Person {
    
    var age: Int {
        willSet {
            print("Person willSet", newValue)
        }
        didSet {
            print("Person didSet", oldValue)
        }
    }
    init() {
        self.age = 0    // 此处不会调用自己的属性观察器
    }
}
var p1 = Person()   // 此次没有打印任何信息

class Person {
    
    var age: Int {
        willSet {
            print("Person willSet", newValue)
        }
        didSet {
            print("Person didSet", oldValue)
        }
    }
    init() {
        self.age = 0    // 此处不会调用自己的属性观察器
    }
}

class Student : Person {
    override init() {
        super.init()
        self.age = 1    // 此处会调用父类的属性观察器
    }
}
// Person willSet 1
// Person didSet 0
var stu1 = Student()

class Person {
    
    var age: Int {
        willSet {
            print("Person willSet", newValue)
        }
        didSet {
            print("Person didSet", oldValue)
        }
    }
    init() {
        self.age = 0    // 此处不会调用自己的属性观察器
    }
}

class Student : Person {
    
    override var age: Int {
        willSet {
            print("Student willSet", newValue)
        }
        didSet {
            print("Student didSet", oldValue)
        }
    }
    
    override init() {
        super.init()
        self.age = 1    // 此处会调用父类的属性观察器
    }
}
//Student willSet 1
//Person willSet 1
//Person didSet 0
//Student didSet 0
var stu1 = Student()

09-可失败初始化器


class Person {
    var name: String
    init?(name: String) {   // 可选项初始化器 在init后面加上?
        if name.isEmpty {
            return nil
        }
        self.name = name
    }
}

var p1 = Person(name: "")
print(p1)   // nil

var p2 = Person(name: "Liwx")
print(p2)   // Optional(__lldb_expr_2.Person)

// Int可失败初始化器定义
// public Init?(_ description: String)
var num1 = Int("123")
print(num1) // Optional(123)
var num2 = Int("abc")
print(num2) // nil

enum Answer : Int {
    case wrong, right
}

var answer1 = Answer(rawValue: 1)
print(answer1)  // Optional(__lldb_expr_13.Answer.right)
var answer2 = Answer(rawValue: 100)
print(answer2)  // nil

class Person {
    var name: String
    init?(name: String) {   // 可选项初始化器 在init后面加上?
        if name.isEmpty {
            return nil
        }
        self.name = name
    }
    // 不允许同时定义参数标签、参数个数、参数类型相同的可失败初始化器和非可失败初始化器
//    init(name: String) {    // error: invalid redeclaration of 'init(name:)'
//        self.name = name
//    }
}

class Person {
    var name: String
    init!(name: String) {   // 可选项初始化器 在init后面加上?
        if name.isEmpty {
            return nil
        }
        self.name = name
    }
}

var p1 = Person(name: "")
print(p1)   // nil

var p2 = Person(name: "Liwx")
print(p2)   // Optional(__lldb_expr_16.Person)

class Person {
    var name: String
    convenience init?(name: String) {
        // 可失败初始化器可以调用非可失败初始化器
        self.init()
        
        if name.isEmpty {
            return nil
        }
    }
    
    init() {
        self.name = ""
    }
}

var p1 = Person(name: "")
print(p1)   // nil
var p2 = Person(name: "Liwx")
print(p2)   // Optional(__lldb_expr_19.Person)

class Person {
    var name: String
    
    init?(name: String) {
        if name.isEmpty {
            return nil
        }
        self.name = name
    }

    convenience init() {
        // 非可失败初始化器调用可失败初始化器需要进行解包
        self.init(name: "")!
    }
    
    // 这样也可以
//    init!(name: String) {
//        if name.isEmpty {
//            return nil
//        }
//        self.name = name
//    }
//
//    convenience init() {
//        // 非可失败初始化器调用可失败初始化器需要进行解包
//        self.init(name: "")
//    }
}
var p1 = Person()
print(p1)   // error: Unexpectedly found nil while unwrapping an Optional value

class Person {
    var name: String
    
    init?(name: String) {
        if name.isEmpty {
            return nil
        }
        self.name = name
    }

    convenience init?() {
        // 非可失败初始化器调用可失败初始化器需要进行解包
        self.init(name: "")
        // 可失败初始化器如果初始化失败,以下代码不执行
        self.name = "Liwx"
        print("test")   // 不会打印test
    }
}
var p1 = Person()
print(p1)   // nil

class Person {
    var name: String
    
    init?(name: String) {
        if name.isEmpty {
            return nil
        }
        self.name = name
    }
}

class Student : Person {
    // 可以用一个`非可失败初始化器` `重写`一个`可失败初始化器`
    override init(name: String) {
        // 因为没有调用super,所以报错 error: 'super.init' isn't called on all paths before returning from initializer
    }
}

class Person {
    var name: String
    
    init(name: String) {
        self.name = name
    }
}

class Student : Person {
    // 不可以用一个`可失败初始化器` `重写`一个`非可失败初始化器`
    // error: failable initializer 'init(name:)' cannot override a non-failable initializer
    override init?(name: String) {
        super.init(name: name)
    }
}

10-反初始化器(deinit)

class Person {
    deinit {
        print("Person deinit")  // 实例对象被释放会调用deinit
    }
}
func test() {
    var p1 = Person()
}
print("1")  // 1
test()      // Person deinit
print("2")  // 2

class Person {
    deinit {
        print("Person deinit")
    }
}

class Student : Person {
    deinit {
        print("Student deinit")
    }
}
func test() {
    var stu1 = Student()
}

// 1
// Student deinit
// Person deinit
// 2
print("1")
test()
print("2")

iOS Swift 语法 底层原理内存管理分析 专题:【iOS Swift5语法】

下一篇: 敬请期待
上一篇: 11 - 继承


上一篇下一篇

猜你喜欢

热点阅读