Swift学习01:自定义Log

张建 lol

打印文件名、方法、行数

1
2
3
4
5
6
7
8
9
10
11
// 1.获取打印所在的文件
let file = (#file as NSString).lastPathComponent;
print(file);

// 2.获取打印所在的方法
let function = #function
print(function);

// 3.获取打印所在的行号
let line = #line;
print(line)

全局化

swift 中的 全局函数:写在单独的一个 .swift 文件下即可,比如:Common.swift

1
2
3
4
5
6
7
func ZNLog<T>(message:T, file:String = #file, funcName:String = #function, lineNum:Int = #line) {

let fileName = (file as NSString).lastPathComponent;

print("[文件名:\(fileName)]:[函数名:\(funcName)]:[行数:\(lineNum)]-打印内容:\n\(message)");

}

配置DeBug下打印,Release 下不打印

  • Swift 没有宏定义,只能通过添加配置字段,Build Settings -> Other Swift Flags 下添加 -D DEBUG

最终写法

1
2
3
4
5
6
7
// 自定义Log
func MyLog<T>(message: T,file: String = #file, funcName: String = #function, lineNum: Int = #line) {
#if DEBUG
let fileName = (file as NSString).lastPathComponent
print("[文件名:\(fileName)]:[函数名:\(funcName)]:[行数:\(lineNum)]-打印内容:\n\(message)");
#endif
}
  • Post title:Swift学习01:自定义Log
  • Post author:张建
  • Create time:2023-03-15 04:26:24
  • Post link:https://redefine.ohevan.com/2023/03/15/Swift/Swift学习01:自定义Log/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.