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)
/**
* "Person(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,diameter:Double = 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,diameter:Double = 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 出来的信息,方便了调试.
网友评论