Macros in Swift? Macros in Swift? swift swift

Macros in Swift?


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.


The Apple docs state that:

Declare simple macros as global constants, and translate complex macros into functions.

You can still use #if/#else/#endif - but my feeling is that they will not introduce macro functions, the language simply doesn't need it.


Since XCode 7.3, the __FILE__ __FUNCTION__ and __LINE__ compile-time constants have become the nicer-looking #file #function and #line respectively.