对于一个对象:
class PersonItem: ContactItem { var personType:PersonType var phoneNumber:String var email:String var position:String }
之前打印都是:
print("parsed out: /(newPersonItem.type) /(newPersonItem.personType) /(newPersonItem.name) /(newPersonItem.id)") gLog.debug("parse out /(personItem.phoneNumber) /(personItem.email) /(personItem.position) /(personItem.headerBkgColor) /(personItem.headerImage) /(personItem.headerImageLarge)")
很是麻烦。
想要去添加支持,使得对于print对象,可以自动打印出对应的基本信息
【解决过程】
1.搜:
swift print object description
What is the Swift equivalent of -[NSObject description]? – Stack Overflow
swift – Getting description like NSObject – Stack Overflow
How can I change the textual representation displayed for a type in Swift? – Stack Overflow
Textual Representation for Classes in Swift – Venkat Peri
2.搜:
swift DebugPrintable
Swifter – Swift 必备 tips
http://swifter.tips/print/
ios – Implementing debugDescription for DebugPrintable in Swift – Stack Overflow
cocoa – Difference between Printable and DebugPrintable in Swift – Stack Overflow
变成:
class ContactItem:NSObject, NSCoding, CustomStringConvertible { var type:ContactType // person/group/topic id string var id:String // person name/group title/topic title var name:String var headerBkgColor:UIColor //30x30, person/group/topic header image var headerImage:UIImage //41x41, for conversation/personal info/... use, larger size image var headerImageLarge:UIImage //used for SelectPersonViewController var selected:Bool //used for indicated whether some info is updated var isUpdated:Bool override var description: String { return "/(super.description),type=/(type),id=/(id),name=/(name),headerBkgColor=/(headerBkgColor),headerImage=/(headerImage),headerImageLarge=/(headerImageLarge),selected=/(selected),isUpdated=/(isUpdated)" } class PersonItem: ContactItem{ var personType:PersonType var phoneNumber:String var email:String var position:String override var description: String { return "/(super.description),personType=/(personType),phoneNumber=/(phoneNumber),email=/(email),position=/(position)" }
之后,代码:
gLog.debug("personItem=/(personItem)")
即可输出完整的信息了:
【总结】
给对象加上继承符合CustomStringConvertible 协议,然后实现对应的var description: String即可
比如:
class ContactItem:NSObject, NSCoding, CustomStringConvertible { var id:String // person name/group title/topic title var name:String override var description: String { return "/(super.description),id=/(id),name=/(name)" } }
即可。
这样以后再去用print(或者别的log函数)去打印该变量,就不会再输出:
xxx Object
而是输出对应的description的string值了。