美文网首页
Swift5.1学习随笔之打印print、debugPrint

Swift5.1学习随笔之打印print、debugPrint

作者: SAW_ | 来源:发表于2020-05-14 09:59 被阅读0次

    一般来说,开发中需要在控制台输出信息查看的时候,用到print就可以

    print("123") // 123
    

    如果想让print输出的东西能表现更多信息,就需要自定义输出了,那么就要保证实例遵守CustomStringConvertible协议,就可以重写printdescription描述

    class Person: CustomStringConvertible {
        var age = 0
        var description: String {
            "person_\(age)"
        }
    }
    var p = Person()
    print(p) // person_0
    

    相应的,系统还提供了另外一个输出的协议CustomDebugStringConvertible,对应着debugPrint

    class Person: CustomDebugStringConvertible {
        var age = 0
        var debugDescription: String {
            "person_debug_\(age)"
        }
    }
    var p = Person()
    debugPrint(p) // person_debug_0
    

    基本上两个print是没有什么区别的:

    • print调用的是CustomStringConvertible协议的description
    • debugPrintpo(控制台断点调试的时候,po会优先调用debugPrint)调用的是CustomDebugStringConvertible协议的debugDescription

    相关文章

      网友评论

          本文标题:Swift5.1学习随笔之打印print、debugPrint

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