It is convenient to use a static logging function which automatically prints both the values of the parameters, but also details about where the log call was made, to aid debugging.
e.g. call at line 999 in function someFunctionName() in file User/QiitaUser/project/someFileName.swift
log(someDouble, someCustomObject)
The Xcode Application output is:
someFileName -> line 999 -> someFunctionName -> someDouble, someCustomObject values...
Here, we take advantage the protocol CustomDebugStringConvertible. All native types (string, double) conform to this protocol, and so will show useful information when printing e.g. someDouble.debugDescription, String(reflecting: someDouble). It is also simple to conform custom objects to this protocol in their definition.
See https://developer.apple.com/documentation/swift/customdebugstringconvertible for official implementation details for CustomDebugStringConvertible
// call the function with the "args" paremter only - the other paramters are assigned automatically
static func log(_ args: Any?..., tag: String = "", file: String = #file, function: String = #function, line: Int = #line) {
// define a value for DEBUG_LOGGING in Build Settings -> Active Compilation Conditions for the debug target
#if DEBUG_LOGGING
// extract the calling filename from the complete path, or the complete path, as necessary
let parsedFileName = String(file.split(separator: "/").last?.split(separator: ".").first ?? "")
let fileName = (parsedFileName.isEmpty) ? file : parsedFileName
// extract the calling function name from a string containing the arguments and enclosing brackets
let functionName = String(function.split(separator: "(").first ?? "")
// this line defines the location of the log statement
let header = fileName + "-> line " + String(line) + " -> " + functionName
// extract the arguments which conform to CustomDebugStringConvertible, and combine their
// descriptions via reflection
let argsAsString = args
.compactMap{$0 as? CustomDebugStringConvertible}
.map{
String(reflecting: $0).replacingOccurrences(of: "Optional", with: "")
}
.joined(separator: " ")
// print to the Application Output
Swift.print(text + " " + argsAsString)
#endif
}