1

I busy rewriting an app in Swift and would like to convert the following macro to Swift code.

#define FLOG(format, ...)               NSLog(@"%@.%@ %@", [self class], NSStringFromSelector(_cmd), [NSString stringWithFormat:format, ##__VA_ARGS__])

How can I define this as a Swift function such that I can use if anywhere for debug logging purposes, or is there an alternate way to achieve the same thing?

Duncan Groenewald
  • 8,496
  • 6
  • 41
  • 76

2 Answers2

0

The easiest way is probably to take advantage of string interpolation and use:

func FLOG(message:String, method:String = __FUNCTION__) {
    println("\(method): \(message)")
}

Then you usage is similar to:

FLOG("Illegal value: \(value)")

Having the method argument default to __FUNCTION__ means that it will normally be replaced with the calling function name. Other automatic variables that you could use include __FILE__, __LINE__ and __COLUMN__. Unfortunately __PRETTY_FUNCTION__ is no longer available.

If you want more control over the formatting of the message than string interpolation allows, take a look at this question which demonstrates simplifying access to printf-style formatting in Swift, and would let you do:

FLOG("Illegal value: %x" % [value])

See also this post from Apple that addresses using __FILE__ and __LINE__ in assert

Community
  • 1
  • 1
David Berry
  • 40,941
  • 12
  • 84
  • 95
  • thanks I guess that solves the method part, but how should one define a global function - presumably one can't define a global function like one can define a global variable. Is it best to define a Singleton class with this (and other helper) function(s) ? – Duncan Groenewald Oct 04 '14 at 02:23
  • I would just define this as a global function. Theres really no reason not to. – David Berry Oct 04 '14 at 04:25
0

Apple's answer to the removal of macros and something new to replace them is that nothing like macros will be available in swift. The closest you can get is to replace #define with a global let variable.

Example: instead of #define CONSTANT 0 you can write let CONSTANT = 0

Whereas, if you want to pass arguments inside a macro, that feature will no longer be available as considered bad programming practice. What you can do instead is create a function.