美文网首页
Swift 如何获取当前代码的函数名和行号

Swift 如何获取当前代码的函数名和行号

作者: sampson6688 | 来源:发表于2021-10-18 15:40 被阅读0次

#file 用于获取当前文件文件名
#line 用于获取当前行号
#column 用于获取当前列编号
#function 用于获取当前函数名

写一个调试输出日志的方法:

func printLog(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, funcName: String = #function, line: Int = #line) {
    #if DEBUG || UAT
        let fileName = (file as NSString).lastPathComponent
        let output = items.map { "\($0)" }.joined(separator: separator)
        let dateString = StringFormatterUtils.dateToString(Date(), dateFormat: "yyyy/MM/dd HH:mm:ss")
        Swift.print("[\(dateString)][\(fileName)][\(funcName)][Line-\(line)] \(output)", terminator: terminator)
    #endif
}

工具类StringFormatterUtils

struct StringFormatterUtils {
    static func stringToDate(_ string: String, dateFormat: String = "yyyyMMdd") -> Date? {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(identifier: "Asia/Tokyo")
        formatter.dateFormat = dateFormat
        let date = formatter.date(from: string)
        return date
    }

    static func dateToString(_ date: Date, dateFormat: String = "yyyy/MM/dd") -> String {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(identifier: "Asia/Tokyo")
        formatter.dateFormat = dateFormat
        let date = formatter.string(from: date)
        return date
    }

    static func stringToDateString(_ string: String, fromFormat: String = "yyyyMMdd", toFormat: String = "yyyy/MM/dd") -> String {
        let fromFormatter = DateFormatter()
        fromFormatter.locale = Locale(identifier: "en_US_POSIX")
        fromFormatter.timeZone = TimeZone(identifier: "Asia/Tokyo")
        fromFormatter.dateFormat = fromFormat
        let date = fromFormatter.date(from: string)

        let toFormatter = DateFormatter()
        toFormatter.locale = Locale(identifier: "en_US_POSIX")
        toFormatter.timeZone = TimeZone(identifier: "Asia/Tokyo")
        toFormatter.dateFormat = toFormat

        let dateStr = toFormatter.string(from: date ?? Date())
        return dateStr
    }
}

相关文章

网友评论

      本文标题:Swift 如何获取当前代码的函数名和行号

      本文链接:https://www.haomeiwen.com/subject/ufjnoltx.html