CustomStringConvertible 和CustomDebugStringConvertible这两个协议类似于Objective-C中的重写description方法,继承协议 实现description 和 debugDescription 属性 即可打印出想要的数据内容。接下来我们来看一下这两个协议在Swift中的利用:
1 .Struct 中的应用
起首我们界说一个结构体,输出这个结构体,看 print 的效果:
struct Person { var age: Int var name: String var job: String}let meetings = Person(age: 24, name: "haha", job: "iOSDeveloper")print(meetings)/** * "erson(age: 24, name: "haha", job: "iOSDeveloper")\n" */接下来我们让这个结构体继承自CustomStringConvertible 和CustomDebugStringConvertible这两个协议,检察输出效果:
struct Person:CustomStringConvertible,CustomDebugStringConvertible { var age: Int var name: String var job: String var description: String { return "\(age) \(name) \(job)" } var debugDescription: String { return "\(name) \(age) \(job)" }}let meetings = Person(age: 24, name: "haha", job: "iOSDeveloper")print(meetings)/** * "24 haha iOSDeveloper\n" */debugPrint(meetings)/** * "haha 24 iOSDeveloper\n" */通过这两个协议就可以自界说输出的参数,如许在调试的时间就会方便很多。
2 .Class 中的应用
界说一个类的话, 当我们利用print 时间并不会输出类中的变量
class Wheel { var spokes: Int = 0 var diameter: Double = 0.0 init(spokes:Int = 32,diameterouble = 26.0) { self.spokes = spokes self.diameter = diameter } func removeSpokes() { spokes = spokes > 0 ? spokes-- : spokes }}var wheel = Wheel(spokes: 36,diameter: 29)print(wheel)/** * "Wheel\n" */如果想要改变 print 的输出效果,我们必要让类服从这两个协议,最好用 Extension
class Wheel { var spokes: Int = 0 var diameter: Double = 0.0 init(spokes:Int = 32,diameterouble = 26.0) { self.spokes = spokes self.diameter = diameter } func removeSpokes() { spokes = spokes > 0 ? spokes-- : spokes }}extension Wheel: CustomDebugStringConvertible,CustomStringConvertible { var description: String { return "wheel has \(spokes) spokes" } var debugDescription: String { return "wheel has \(spokes) spokes spokes " }}var wheel = Wheel(spokes: 36,diameter: 29)print(wheel)/** * "wheel has 36 spokes\n" */debugPrint(wheel)/** * "wheel has 36 spokes spokes \n" */3 ViewController,NSObject 中的应用
如果想要改变一个 ViewController 中的 print 方法,先看默认的输出效果
class WheelsViewController: UIViewController { var wheels = [Wheel]()}var wheels = WheelsViewController()print(wheels)/** * "<__lldb_expr_124.WheelsViewController: 0x7fb91a634dc0>\n" */这里只输出了className 的内存所在,如果想要改变,并不能用 Extension 的方法,由于 UIViewController已经继承了这两个协议,那么就只能用 override 来实现 DIY 的 print
class WheelsViewController: UIViewController { var wheels = [Wheel]()}extension WheelsViewController { override var description: String { return "wheelsViewController has \(wheels)" } override var debugDescription: String { return "DEBUG__wheelsViewController has \(wheels)" }}var w = WheelsViewController()w.wheels = [wheel]print(w)/** * "wheelsViewController has [wheel has 36 spokes spokes ]\n" */debugPrint(w)/** * "DEBUG__wheelsViewController has [wheel has 36 spokes spokes ]\n" */如许就得到了我们想要 print 出来的信息,方便了调试.
转自:https://www.jianshu.com/p/855dd6aa7ec1 |