完整代码如下:
import Foundation
class LauCouponManager: CustomStringConvertible {
static let shared = LauCouponManager()
init() {
}
var description: String{
return "address:\(Unmanaged.passUnretained(self).toOpaque())"
}
}
在Swift中,类可以没有父类,如果继承自NSObject的类,可以直接使用description来打印地址,但是如果没有父类,那么这个类就要遵循一个协议:CustomStringConvertible
该协议的源文件介绍如下:
/// - SeeAlso: `String.init<T>(T)`, `CustomDebugStringConvertible`
public protocol CustomStringConvertible {
/// A textual representation of this instance.
///
/// Instead of accessing this property directly, convert an instance of any
/// type to a string by using the `String(describing:)` initializer. For
/// example:
///
/// struct Point: CustomStringConvertible {
/// let x: Int, y: Int
///
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(describing: p)
/// print(s)
/// // Prints "(21, 30)"
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `description` property.
public var description: String { get }
}
有一个公用的只读属性description,在这个方法里面返回的也是字符串,可以用来打印调试.
如果打印地址:需要用
Unmanaged.passUnretained("your object").toOpaque()
your object就是你想要打印地址的对象