Macros in Swift?

Solution 1:

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.

Solution 2:

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.

Solution 3:

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

Solution 4:

Here is an updated Swift 2 answer.

func LogW(msg:String, function: String = #function, file: String = #file, line: Int = #line){
    print("[WARNING]\(makeTag(function, file: file, line: line)) : \(msg)")
}

private func makeTag(function: String, file: String, line: Int) -> String{
    let url = NSURL(fileURLWithPath: file)
    let className = url.lastPathComponent ?? file
    return "\(className) \(function)[\(line)]"
}

Example of use:

LogW("Socket connection error: \(error)")

Solution 5:

lastPathComponent needs an NSURL, so I changed the above code to this:

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

        let url = NSURL(fileURLWithPath: file)

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

log("some message")