iOS开发中Log打印是最为常见的调试方式,没有之一. Swift提供了两种打印方式
public func print(_ items: Any..., separator: String = default, terminator: String = default)public func debugPrint(_ items: Any..., separator: String = default, terminator: String = default)复制代码
debugPrint可以自己识别是否是release环境,如果是release环境就不会打印 虽然Swift贴心的提供了debugPrint这个方法,但是对于Log太多的项目来说,找到自己的打印信息还是费点眼睛的. 如果打印出时间,文件,方法那么就更好了 废话不多说,直接上代码 首先需要在Build Setting -> Other Swift Flags设置一下
public func OKPrint( _ object: @autoclosure() -> Any?, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { #if DEBUG guard let value = object() else { return } var stringRepresentation: String? if let value = value as? CustomDebugStringConvertible { stringRepresentation = value.debugDescription } else if let value = value as? CustomStringConvertible { stringRepresentation = value.description } else { fatalError("gLog only works for values that conform to CustomDebugStringConvertible or CustomStringConvertible") } let gFormatter = DateFormatter() gFormatter.dateFormat = "HH:mm:ss:SSS" let timestamp = gFormatter.string(from: Date()) let queue = Thread.isMainThread ? "UI" : "BG" let fileURL = NSURL(string: file)?.lastPathComponent ?? "Unknown file" if let string = stringRepresentation { print("✅ \(timestamp) {\(queue)} \(fileURL) > \(function)[\(line)]: \(string)") } else { print("✅ \(timestamp) {\(queue)} \(fileURL) > \(function)[\(line)]: \(value)") } #endif}复制代码