Macros in Swift?

jhurliman picture jhurliman · Jun 9, 2014 · Viewed 36.7k times · Source

Does Swift currently support macros, or are there future plans to add support? Currently I'm scattering:

Log.trace(nil, function: __FUNCTION__, file: __FILE__, line: __LINE__)

In various places throughout my code.

Answer

Sulthan picture Sulthan · Jun 9, 2014

In this case you should add a default value for the "macro" parameters.

Swift 2.2 and higher

func log(message: String,
        function: String = #function,
            file: String = #file,
            line: Int = #line) {

     print("Message \"\(message)\" (File: \(file), Function: \(function), Line: \(line))")
}

log("Some message")

Swift 2.1 and lower

func log(message: String,
        function: String = __FUNCTION__,
        file: String = __FILE__,
        line: Int = __LINE__) {

    print("Message \"\(message)\" (File: \(file.lastPathComponent), Function: \(function), Line: \(line))")
}

log("Some message")

This is what fatalError and assert functions do.

There are no other macros except the conditional compilation already mentioned in another answer.