美文网首页
CustomStringConvertible Self

CustomStringConvertible Self

作者: 纳兰沫 | 来源:发表于2019-09-25 17:16 被阅读0次

    CustomStringConvertible

    遵守CustomStringConvertible CustomDebugStringConvertible都可以实现自定义打印字符串
    
    class Person: CustomStringConvertible,CustomDebugStringConvertible {
        var age = 0
        var description: String {
            return "person_\(age)"
        }
        var debugDescription: String {
            return "debug_person_\(age)"
        }
    }
    
    var person = Person()
    print(person)
    debugPrint(person)
    
    print调用的是CustomStringConvertible协议的description
    debugPrint调用的是CustomDebugStringConvertible协议的debugDescription方法
    

    Self

    代表当前类型
    class Person {
        
        var age = 1
        static var count = 2
        func run() {
            print(self.age)
            print(Self.count)
        }
    }
    

    self 代表谁调用这个方法 他就是谁
    Self 代表Person这个类型 调用类型属性 类型方法

    一般用作返回值类型 限定返回值跟方法调用者必须是同一类型(也可作为参数类型)
    protocol Runnable {
        func test() -> Self
    }
    
    class Person: Runnable {
        required init() {
            
        }
        
        func test() -> Self {
            return type(of: self).init()
        }
    }
    
    class Student: Person {
        
    }
    
    
    var p = Person()
    print(p.test())
    
    var stu = Student()
    print(stu.test())
    
    
    swiftTest.Person
    swiftTest.Student
    

    断言

    不符合指定条件就抛出运行时错误 常用于调试阶段(Debug)阶段的判断
    

    默认情况下,断言只会在debug模式下生效 release模式下没有效果
    无法通过do-catch捕捉错误

    func divide(_ v1: Int, _ v2: Int) -> Int {
        
        assert(v2 != 0, "除数不能为0")
        return v1 / v2
    }
    
    print(divide(20, 0))
    
    错误信息.png

    如果需要在release模式下开启断言 可以在Swift Flags的Release里面设置assert-config Debug
    如果需要在debug模式下强制关闭断言 就再Debug里面设置assert-config Release

    如何强制打开或者关闭断言.png

    fatalError

    如果遇到严重问题 希望结束程序运行时 可以直接使用fatalError函数抛出错误(这是无法通过do-catch捕捉的错误)
    
    func test(_ num: Int) -> Int {
        
        if num >= 0 {
            return 1
        }
        fatalError("num 不能小于0")
    }
    
    test(-1)
    
    fatalError错误.png

    在某些不得不实现 但不希望别人调用的方法 可以考虑内部使用fatalError函数

    class Person {
        required init() {
            
        }
    }
    
    class Student: Person {
        
        required init() {
            fatalError("don't call Student.init")
        }
        init(score: Int) {
            
        }
    }
    
    var stu1 = Student(score: 98)
    var stu2 = Student()
    
    
    内部使用fatalError.png

    fatalError assert区别

    1. fatalError 不需要写return assert还是需要的
    2. fatalError 不管在debug 还是release都可以使用 
       assert在release无法使用 只能在debug使用 (除非强制设置在release开启断言)
    

    do-catch 可以对错误进行捕捉进行一些补救 友善的提示
    fatalError assert抛出无法挽救的错误 直接结束程序的时候使用

    相关文章

      网友评论

          本文标题:CustomStringConvertible Self

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